Skip to content

Instantly share code, notes, and snippets.

@mkuklis
Created July 31, 2018 17:53
Show Gist options
  • Save mkuklis/67d8b95aa948d4f3f1e41e5554dc7056 to your computer and use it in GitHub Desktop.
Save mkuklis/67d8b95aa948d4f3f1e41e5554dc7056 to your computer and use it in GitHub Desktop.
AWS Lambda for image resizing with sharp
const sharp = require('sharp');
const aws = require('aws-sdk');
const s3 = new aws.S3();
const Bucket = "BucketName";
const transforms = [
{ name: 'small', size: 85 },
{ name: 'medium', size: 160 },
{ name: 'large', size: 250 },
];
exports.handler = async (event, context) => {
const key = event.Records[0].s3.object.key;
const sanitizedKey = key.replace(/\+/g, ' ');
const keyWithoutExtension = sanitizedKey.replace(/.[^.]+$/, '');
const parts = key.split('/');
const folder = parts[0];
const file = parts[1];
if (key.match('-size-')) {
return context.succeed();
}
try {
const data = await s3.listObjects({ Bucket, Prefix: `${folder}/` }).promise();
const files = data.Contents;
const Objects = files.reduce((acc, f) => {
if (!f.Key.match(file)) acc.push({ Key: f.Key });
return acc;
}, []);
if (Objects.length) {
await s3.deleteObjects({ Bucket, Delete: { Objects } }).promise();
}
const image = await s3.getObject({ Bucket, Key: sanitizedKey }).promise();
for (const t of transforms) {
const resizedImg = await sharp(image.Body).resize(t.size, t.size).max().toFormat('jpeg').toBuffer();
const updated = await s3.putObject({ Bucket, Body: resizedImg, Key: `${keyWithoutExtension}-size-${t.name}.jpg` }).promise();
}
context.succeed();
}
catch(err) {
context.fail(`Error resizing files: ${err}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment