Skip to content

Commit 55df9ac

Browse files
committed
use jpgeg-js
1 parent 643f3e1 commit 55df9ac

3 files changed

Lines changed: 34 additions & 9 deletions

File tree

src/index.js

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
const AWS = require('aws-sdk');
22
const Busboy = require('busboy');
3-
const Jimp = require('jimp');
3+
const jpeg = require('jpeg-js'); // A lightweight library for encoding/decoding JPEG images
44

55
const 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
5053
const 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+
85108
module.exports = { handler };

src/package-lock.json

Lines changed: 2 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
"aws-sdk": "^2.1692.0",
1515
"busboy": "^1.6.0",
1616
"jest": "^29.7.0",
17-
"jimp": "^1.6.0"
17+
"jimp": "^1.6.0",
18+
"jpeg-js": "^0.4.4"
1819
}
1920
}

0 commit comments

Comments
 (0)