Skip to content

Instantly share code, notes, and snippets.

@csoni111
Created March 4, 2019 09:35
Show Gist options
  • Save csoni111/8b2303163bc24105eb73122fbcc3cdb7 to your computer and use it in GitHub Desktop.
Save csoni111/8b2303163bc24105eb73122fbcc3cdb7 to your computer and use it in GitHub Desktop.
Sample Lambda Code for Image Conversion on S3
'use strict';
const AWS = require('aws-sdk');
const S3 = new AWS.S3({ apiVersion: '2006-03-01' });
const Sharp = require('sharp');
const outputBucket = 'output-bucket-name';
const config = [
{
'key': 'small',
'maxHeight': 320,
'format': 'webp',
'options': {'quality': 100}
},
{
'key': 'med',
'maxHeight': 640,
'format': 'webp',
'options': {'quality': 100}
},
{
'key': 'large',
'maxHeight': 960,
'format': 'webp',
'options': {'quality': 100}
},
{
'key': 'preview',
'maxHeight': 42,
'format': 'webp',
'options': {'quality': 10}
}
];
let resizeParams = {
fit: Sharp.fit.inside,
withoutEnlargement: true
};
exports.handler = (event, context, callback) => {
// get the bucket name for uploaded image
const bucket = event.Records[0].s3.bucket.name;
// get the path for the uploaded image
const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
console.log('New image uploaded: ', key);
// get filename by removing the extension
const name = key.split('.')[0];
const params = {
Bucket: bucket,
Key: key,
};
// get the image data from S3
S3.getObject(params).promise().then(data => {
const image = data.Body;
let promises = [];
console.log('image data fetched');
// iterate over output image configurations
for (let i = 0; i < config.length; i++) {
let c = config[i];
// set the height param to max allowed height for current config
resizeParams['height'] = c['maxHeight'];
// resize the image using Sharp
let bufferPromise = Sharp(image).resize(resizeParams).toFormat(c['format'], c['options']).toBuffer()
let s = Promise.all([bufferPromise, c])
.then(([buffer, c]) => {
// put the new image back in S3 output bucket
return S3.putObject({
Body: buffer,
Bucket: outputBucket,
ContentType: `image/${c['format']}`,
Key: `resized/${name}-${c['key']}.${c['format']}`
}).promise()
});
promises.push(s);
}
return Promise.all(promises);
})
.then(() => {
callback(null, 'success');
})
.catch(err => {
console.log('error: ', err);
callback(`error: ${err}`);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment