Skip to content

Instantly share code, notes, and snippets.

@igor9silva
Created May 31, 2023 11:11
Show Gist options
  • Save igor9silva/b088edf38a7e414f7285650e33cca677 to your computer and use it in GitHub Desktop.
Save igor9silva/b088edf38a7e414f7285650e33cca677 to your computer and use it in GitHub Desktop.
Generate Thumbnail on S3 upload
// dependencies
const util = require('util');
const sharp = require('sharp');
const AWS = require('aws-sdk');
// get reference to S3 client
const s3 = new AWS.S3();
exports.handler = async (event, context, callback) => {
// Read options from the event parameter.
console.log("Reading options from event:\n", util.inspect(event, {depth: 5}));
const thumbPrefix = "thumb-";
const srcBucket = event.Records[0].s3.bucket.name;
// Object key may have spaces or unicode non-ASCII characters.
const srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));
const dstBucket = srcBucket;
const dstKey = thumbPrefix + srcKey;
if (srcKey.startsWith(thumbPrefix)) {
console.log("image already processed.");
return;
}
// Download the image from the S3 source bucket.
try {
const params = {
Bucket: srcBucket,
Key: srcKey,
};
const origimage = await s3.getObject(params).promise();
} catch (error) {
console.log(error);
return;
}
// set thumbnail width. Resize will set the height automatically to maintain aspect ratio.
const width = 400;
// Use the Sharp module to resize the image and save in a buffer.
try {
const buffer = await sharp(origimage.Body)
.resize({width: width, withoutEnlargement: true})
.withMetadata()
.toBuffer();
} catch (error) {
console.log(error);
return;
}
// Upload the thumbnail image to the destination bucket
try {
const destparams = {
Bucket: dstBucket,
Key: dstKey,
Body: buffer,
ContentType: "image"
};
const putResult = await s3.putObject(destparams).promise();
} catch (error) {
console.log(error);
return;
}
console.log('Successfully resized ' + srcBucket + '/' + srcKey + ' and uploaded to ' + dstBucket + '/' + dstKey);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment