I have another functional example of when an image enters in bucket S3, it's triggered by a lambda (Node JS) that also uses lib sharp to optimize the image size, and then, publishes the new image in another folder in s3.
Here is an example:
"use strict";
const AWS = require("aws-sdk");
const sharp = require("sharp");
const { basename, extname } = require("path");
const S3 = new AWS.S3();
module.exports.handle = async ({ Records: records }) => {
try {
await Promise.all(
records.map(async (record) => {
const { key } = record.s3.object;
const image = await S3.getObject({ Bucket: process.env.bucket, Key: key }).promise();
// blob
const optimized = await sharp(image.Body)
.resize(1280, 720, {
fit: "inside",
withoutEnlargement: true,
})
.toFormat("jpeg", {
progressive: true,
quality: 50,
})
.toBuffer();
await S3.putObject({
Body: optimized,
Bucket: process.env.bucket,
ContentType: "image/jpeg",
Key: `compressed/${basename(key, extname(key))}.jpg`,
}).promise();
})
);
return {
statusCode: 301,
body: { ok: true },
};
} catch (error) {
return error;
}
};