| const sharp = require('sharp'); |
| const stream = require('stream'); |
|
|
| class ImageProcessor { |
| |
| |
| |
| |
| |
| |
| processImage(input, options = {}) { |
| const { quality = 80, format = 'jpeg' } = options; |
|
|
| try { |
| |
| let sharpInstance = sharp(); |
|
|
| |
| switch (format.toLowerCase()) { |
| case 'jpeg': |
| sharpInstance = sharpInstance.jpeg({ quality: parseInt(quality), mozjpeg: true }); |
| break; |
| case 'png': |
| sharpInstance = sharpInstance.png({ quality: parseInt(quality), compressionLevel: 5 }); |
| break; |
| case 'webp': |
| sharpInstance = sharpInstance.webp({ quality: parseInt(quality), speed: 8 }); |
| break; |
| case 'avif': |
| sharpInstance = sharpInstance.avif({ quality: parseInt(quality), speed: 8 }); |
| break; |
| case 'heif': |
| sharpInstance = sharpInstance.heif({ quality: parseInt(quality), speed: 8 }); |
| break; |
| case 'tiff': |
| sharpInstance = sharpInstance.tiff({ quality: parseInt(quality) }); |
| break; |
| default: |
| throw new Error('Unsupported format'); |
| } |
|
|
| |
| return input.pipe(sharpInstance); |
|
|
| } catch (error) { |
| console.error('Error setting up image processing stream:', error); |
| throw error; |
| } |
| } |
| } |
|
|
| module.exports = new ImageProcessor(); |