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: 1 }); 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();