Skip to content

Commit 35146a0

Browse files
committed
Ensure processed image size is not larger than 5MB
1 parent 42cd6c2 commit 35146a0

File tree

1 file changed

+22
-11
lines changed

1 file changed

+22
-11
lines changed

source/image-handler/image-handler.js

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,17 +22,14 @@ class ImageHandler {
2222
*/
2323
async process(request) {
2424
const originalImage = request.originalImage;
25-
const edits = request.edits;
26-
if (edits !== undefined) {
27-
const modifiedImage = await this.applyEdits(originalImage, edits);
28-
if (request.outputFormat !== undefined) {
29-
await modifiedImage.toFormat(request.outputFormat);
30-
}
31-
const bufferImage = await modifiedImage.toBuffer();
32-
return bufferImage.toString('base64');
33-
} else {
34-
return originalImage.toString('base64');
25+
const defaultEdits = {resize: {width: 1200, fit: 'inside', withoutEnlargement: true}};
26+
const edits = request.edits || defaultEdits;
27+
const modifiedImage = await this.applyEdits(originalImage, edits);
28+
if (request.outputFormat !== undefined) {
29+
await modifiedImage.toFormat(request.outputFormat);
3530
}
31+
const bufferImage = await modifiedImage.toBuffer();
32+
return bufferImage.toString('base64');
3633
}
3734

3835
/**
@@ -73,7 +70,21 @@ class ImageHandler {
7370
}
7471
}
7572
// Return the modified image
76-
return image;
73+
return this.reduceImageSize(image);
74+
}
75+
76+
async reduceImageSize(sharpImage) {
77+
const imageBuffer = await sharpImage.toBuffer();
78+
const metadata = await sharp(imageBuffer).metadata()
79+
if (metadata.size < 5242880) {
80+
return sharpImage
81+
}
82+
83+
const newWidth = parseInt(metadata.width * 0.9);
84+
// Reduce 10% until it is under 5MB
85+
console.log(`Large image size ${metadata.size}. Reducing 10% image width from ${metadata.width} to ${newWidth}...`)
86+
87+
return await this.applyEdits(imageBuffer, { resize: { width: newWidth, fit: 'inside', withoutEnlargement: true }});
7788
}
7889

7990
/**

0 commit comments

Comments
 (0)