Last active
November 12, 2015 10:00
-
-
Save mediaash/a47717679a98eb9a512d to your computer and use it in GitHub Desktop.
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
var im = require('imagemagick'); | |
var aws = require('aws-sdk'); | |
var s3 = new aws.S3({ apiVersion: '2006-03-01' }); | |
exports.handler = function(event, context) { | |
var bucket = event.Records[0].s3.bucket.name; | |
var key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); | |
var params = { | |
Bucket: bucket, | |
Key: key | |
}; | |
s3.getObject(params, function(err, data) { | |
if (err) { | |
console.log(err); | |
var message = "Error getting object " + key + " from bucket " + bucket + | |
". Make sure they exist and your bucket is in the same region as this function."; | |
console.log(message); | |
context.fail(message); | |
} else { | |
var contentType = data.ContentType; | |
var extension = contentType.split('/').pop(); | |
var filename = 'images/' + (key.match(/^origin\/(.+)$/) ? RegExp.$1 : key); | |
im.resize({ | |
srcData: data.Body, | |
format: extension, | |
width: 480 // リサイズする画像サイズを指定 | |
}, function(err, stdout, stderr) { | |
if(err) { | |
context.fail(err); | |
return; | |
} | |
s3.putObject({ | |
Bucket: bucket, | |
Key : filename, | |
Body: new Buffer(stdout, 'binary'), | |
ACL : 'public-read', | |
ContentType: contentType | |
}, function(err, res) { | |
if (err) { | |
context.fail(err); | |
} else { | |
context.succeed(); | |
} | |
}); | |
}); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment