11const AWS = require ( 'aws-sdk' ) ;
22const Busboy = require ( 'busboy' ) ;
3- const Jimp = require ( 'jimp ' ) ;
3+ const jpeg = require ( 'jpeg-js ' ) ; // A lightweight library for encoding/decoding JPEG images
44
55const s3 = new AWS . S3 ( ) ;
66
@@ -12,14 +12,16 @@ const handler = async (event) => {
1212 // Parse the incoming multipart form-data
1313 const buffer = await parseMultipart ( event ) ;
1414
15- // Use Jimp to process the image
16- const image = await Jimp . read ( buffer ) ;
17- image . grayscale ( ) ;
15+ // Decode the JPEG to get raw pixel data
16+ const decodedImage = jpeg . decode ( buffer , { useTArray : true } ) ;
1817
19- // Convert the transformed image to a buffer
20- const transformedBuffer = await image . getBufferAsync ( Jimp . MIME_JPEG ) ;
18+ // Apply grayscale transformation
19+ const grayscaleImage = applyGrayscale ( decodedImage ) ;
2120
22- // Upload the image to S3
21+ // Encode the transformed image back to JPEG
22+ const transformedBuffer = jpeg . encode ( grayscaleImage , 90 ) . data ;
23+
24+ // Upload the transformed image to S3
2325 await s3
2426 . putObject ( {
2527 Bucket : bucketName ,
@@ -47,6 +49,7 @@ const handler = async (event) => {
4749 }
4850} ;
4951
52+ // Function to parse multipart/form-data
5053const parseMultipart = async ( event ) => {
5154 return new Promise ( ( resolve , reject ) => {
5255 const busboy = Busboy ( {
@@ -82,4 +85,24 @@ const parseMultipart = async (event) => {
8285 } ) ;
8386} ;
8487
88+ // Function to apply grayscale transformation
89+ const applyGrayscale = ( decodedImage ) => {
90+ const { data, width, height } = decodedImage ;
91+
92+ // Iterate through every pixel (4 values per pixel: R, G, B, A)
93+ for ( let i = 0 ; i < data . length ; i += 4 ) {
94+ const r = data [ i ] ;
95+ const g = data [ i + 1 ] ;
96+ const b = data [ i + 2 ] ;
97+
98+ // Calculate grayscale value using the luminosity method
99+ const gray = Math . round ( 0.3 * r + 0.59 * g + 0.11 * b ) ;
100+
101+ // Set R, G, and B to the grayscale value
102+ data [ i ] = data [ i + 1 ] = data [ i + 2 ] = gray ;
103+ }
104+
105+ return { data, width, height } ;
106+ } ;
107+
85108module . exports = { handler } ;
0 commit comments