Skip to content

Instantly share code, notes, and snippets.

@danielglh
Created February 22, 2017 09:18
Show Gist options
  • Save danielglh/4f940c2aba28e19e5857db82df24eb8b to your computer and use it in GitHub Desktop.
Save danielglh/4f940c2aba28e19e5857db82df24eb8b to your computer and use it in GitHub Desktop.
Image Transformation with AWS Lambda
"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