Created
February 22, 2017 09:18
-
-
Save danielglh/4f940c2aba28e19e5857db82df24eb8b to your computer and use it in GitHub Desktop.
Image Transformation with AWS Lambda
This file contains hidden or 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"; | |
// Dependencies | |
const async = require("async"); | |
const gm = require("gm").subClass({ | |
imageMagick: true | |
}); | |
const aws = require("aws-sdk"); | |
const s3 = new aws.S3(); | |
exports.handle = (event, context, callback) => { | |
// Get bucket key | |
let imageUserId = event.pathParameters["user_id"]; | |
let imageFile = event.pathParameters["image_file"]; | |
let imageKey = `${imageUserId}/${imageFile}`; | |
// Begin! | |
async.waterfall([ | |
function downloadImage(nextStep) { | |
console.time("DownloadImage"); | |
console.log("Downloading..."); | |
s3.getObject({ | |
Bucket: process.env.BUCKET, | |
Key: imageKey | |
}, nextStep); | |
console.timeEnd("DownloadImage"); | |
}, | |
function transform(response, nextStep) { | |
let imageType = response.ContentType; | |
console.log("Image MIME Type before transformation: " + imageType); | |
let image = gm(response.Body); | |
image.resize(200, 200).quality(60).toBuffer( | |
null, | |
(err, buffer) => { | |
console.timeEnd("TransformImage"); | |
if (err) { | |
nextStep(err); | |
} else { | |
nextStep(null, { | |
type: imageType, | |
image: buffer | |
}); | |
} | |
}); | |
}, | |
function respond(data, nextStep) { | |
console.log("Image MIME Type after transformation: " + data.type); | |
let response = { | |
statusCode: 200, | |
headers: { | |
"Content-Type": data.type | |
}, | |
body: data.image.toString('base64'), | |
isBase64Encoded: true | |
}; | |
callback(null, response); | |
} | |
], (err, result) => { | |
if (err) { | |
console.error(err); | |
} | |
callback(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment