Skip to content

Instantly share code, notes, and snippets.

@takaheraw
Created July 22, 2017 23:17
Show Gist options
  • Save takaheraw/2b91225d9278580bcc8427ff7b582b4d to your computer and use it in GitHub Desktop.
Save takaheraw/2b91225d9278580bcc8427ff7b582b4d to your computer and use it in GitHub Desktop.
s3 thumnail
var async = require('async');
var AWS = require('aws-sdk');
var gm = require('gm').subClass({imageMagick: true});
var util = require('util');
var MAX_WIDTH = 100;
var MAX_HEIGTH = 100;
var s3 = new AWS.S3();
exports.handler = function(event, context, callback){
console.log("Reading options from event:\n", util.inspect(event, {depth: 5}));
var srcBucket = event.Records[0].s3.bucket.name;
var srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));
var dstBucket = process.env.TARGET_BUCKET;
var dstKey = "resized-" + srcKey;
if(srcBucket == dstBucket){
callback("Source and destination buckets are the same.");
return;
}
var typeMatch = srcKey.match(/\.([^.]*)$/);
if(!typeMatch){
callback("Could not determine the image type.");
return;
}
var imageType = typeMatch[1];
if(imageType != "jpg" && imageType != "png"){
callback("Unsupported image type: ${imageType}");
return;
}
async.waterfall([
function download(next){
s3.getObject({
Bucket: srcBucket,
Key: srcKey
},
next);
},
function transform(response, next){
gm(response.Body).size(function(err, size){
var scalingFactor = Math.min(
MAX_WIDTH / size.width,
MAX_HEIGTH / size.height
);
var width = scalingFactor * size.width;
var height = scalingFactor * size.height;
this.resize(width, height).toBuffer(imageType, function(err, buffer){
next(null, response.ContentType, buffer);
}
});
});
},
function upload(contentType, data, next){
s3.putObject({
Bucket: dstBucket,
Key: dstKey,
Body: data,
ContentType: contentType
},
next);
}
], function(err){
if(err){
console.error(
"Unable to resize " + srcBucket + "/" + srcKey +
" and upload to " + dstBucket + "/" + dstKey +
" due to an error:" + err
);
}else{
console.log(
"Successfully resized " +srcBucket + "/" + srcKey +
" and uploaded to " + dstBucket + "/" + dstKey
);
}
callback(null, "message");
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment