File size: 2,044 Bytes
74c33ba 6237115 74c33ba 6237115 74c33ba 6237115 74c33ba 6553147 74c33ba 6237115 74c33ba 6237115 74c33ba 6237115 74c33ba 6237115 74c33ba 6237115 74c33ba | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | const sharp = require('sharp');
const stream = require('stream');
class ImageProcessor {
/**
* Processes an image from a readable stream.
* @param {stream.Readable} input - The incoming stream of image data.
* @param {Object} options - Processing options including quality and format.
* @returns {stream.Readable} - A readable stream of the processed image.
*/
processImage(input, options = {}) {
const { quality = 80, format = 'jpeg' } = options;
try {
// Create a Sharp instance for streaming.
let sharpInstance = sharp();
// Apply format and quality options.
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');
}
// Pipe the input stream to the sharp pipeline and return the output stream.
return input.pipe(sharpInstance);
} catch (error) {
console.error('Error setting up image processing stream:', error);
throw error;
}
}
}
module.exports = new ImageProcessor(); |