Skip to content

Instantly share code, notes, and snippets.

@dabit3
Created July 20, 2020 23:07
Show Gist options
  • Save dabit3/c0e697d26380690498a7633764a95722 to your computer and use it in GitHub Desktop.
Save dabit3/c0e697d26380690498a7633764a95722 to your computer and use it in GitHub Desktop.
Image Resize Lambda Trigger
const sharp = require("sharp");
const aws = require("aws-sdk");
const s3 = new aws.S3();
exports.handler = async function(event, context) {
if (event.Records[0].eventName === "ObjectRemoved:Delete") {
return;
}
const BUCKET = event.Records[0].s3.bucket.name;
const KEY = event.Records[0].s3.object.key;
try {
let image = await s3.getObject({ Bucket: BUCKET, Key: KEY }).promise();
image = await sharp(image.Body);
const metadata = await image.metadata();
if (metadata.width > 1000) {
const resizedImage = await image.resize({ width: 1000 }).toBuffer();
await s3.putObject({ Bucket: BUCKET, Body: resizedImage, Key: KEY }).promise();
return;
} else {
return;
}
} catch (err) {
context.fail(`Error resizing image: ${err}`);
}
}
/**
{
"name": "S3Triggere4cecfe5",
"version": "2.0.0",
"description": "Lambda function generated by Amplify",
"main": "index.js",
"license": "Apache-2.0",
"scripts": {
"install": "npm install --arch=x64 --platform=linux sharp"
},
"dependencies": {
"sharp": "^0.23.2"
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment