-
-
Save tarasowski/b1f6081b9e1b2b516f0a4609a3658cea to your computer and use it in GitHub Desktop.
#Lambda - Sample Code: Resizing Images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const AWS = require('aws-sdk') | |
const gm = require('gm').subClass({ imageMagick: true}) | |
const util = require('util') | |
const path = require('path') | |
const parse = require('./parse') | |
const s3 = new AWS.S3() | |
// constants | |
const WEB_WIDTH_MAX = 150 | |
const WEB_HEIGHT_MAX = 150 | |
const download = (bucket, key) => { | |
return s3.getObject({ | |
Bucket: bucket, | |
Key: key | |
}).promise() | |
.then(data => data.Body) | |
.catch(err => err) | |
} | |
const transformWebax = (response) => { | |
return new Promise((resolve, reject) => { | |
gm(response) | |
.resize(WEB_WIDTH_MAX, WEB_HEIGHT_MAX) | |
.gravity('Center') | |
.crop(WEB_WIDTH_MAX, WEB_HEIGHT_MAX) | |
.toBuffer('jpg', function (err, buffer) { | |
if (err) { | |
reject(err) | |
} else { | |
resolve(buffer) | |
} | |
}) | |
}) | |
} | |
const uploadWebMax = (buffer, imageName, dstBucket) => { | |
const dstKeyResized = 'resized/' + imageName | |
return s3.putObject({ | |
Bucket: dstBucket, | |
Key: dstKeyResized, | |
Body: buffer, | |
}).promise() | |
.then(() => 'New resized image was uploaded') | |
.catch(err => console.error(err)) | |
} | |
module.exports.handler = async (event, context, callback) => { | |
const srcBucket = parse.bucketName(event) | |
const srcKey = parse.fileName(event) | |
const imageName = path.basename(srcKey) | |
const dstBucket = srcBucket | |
const typeMatch = srcKey.match(/\.([^.]*)$/) | |
if (!typeMatch) { | |
callback('Could not determinse the image type') | |
} | |
const imageType = typeMatch[1] | |
if (imageType.toUpperCase() !== 'jpg'.toUpperCase() && imageType.toUpperCase() !== 'png'.toUpperCase() && imageType.toUpperCase() !== 'jpeg'.toUpperCase()) { | |
callback(`Unsupported image type: ${imageType}`) | |
return | |
} | |
try { | |
const response = await download(srcBucket, srcKey) | |
const buffer = await transformWebax(response) | |
const upload = await uploadWebMax(buffer, imageName, dstBucket) | |
console.log(upload) | |
callback(null, 'success') | |
} catch (err) { | |
callback(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment