Im invoking a lambda function to compress images uploaded to a bucket and then write the compressed image to another bucket
The code executes fine it fetches the image but for some reason it fails to write the compressed image to the new bucket
Here is my code:
//Import compress module
const imagemin = require('imagemin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const sharp = require('sharp');
const AWS = require('aws-sdk')
const s3 = new AWS.S3()
exports.handler = async (event) =>{
// TODO implement
const srcBucket = event.Records[0].s3.bucket.name;
const srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));
const dstBucket = "safarni";
const dstKey = srcKey;
console.log(srcKey, dstBucket, dstKey)
// Download the image from the S3 source bucket.
try {
const params = {
Bucket: srcBucket,
Key: srcKey
};
var origimage = await s3.getObject(params).promise();
} catch (error) {
console.log('here');
return;
}
const jpgBuffer = await sharp(origimage.Body).jpeg().toBuffer()
//Compressing the photo
const compressedjpgBuffer = await imagemin.buffer(jpgBuffer, {
plugins: [imageminMozjpeg({ quality: 85 })]
})
console.log(compressedjpgBuffer)
// Upload the thumbnail image to the destination bucket
try {
const destparams = {
Bucket: dstBucket,
Key: dstKey,
Body: compressedjpgBuffer,
};
const putResult = await s3.putObject(destparams).promise();
} catch (error) {
console.log(error);
return;
}
console.log('Successfully resized ' + srcBucket + '/' + srcKey +
' and uploaded to ' + dstBucket + '/' + dstKey);
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};

