Created
March 2, 2016 12:03
-
-
Save yamano/198a5543da51d52898c5 to your computer and use it in GitHub Desktop.
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
console.log('Loading function'); | |
const HEIGHT = 370; | |
const WIDTH = 320; | |
var fs = require('fs'); | |
var gm = require('gm').subClass({ imageMagick: true }); | |
var aws = require('aws-sdk'); | |
var s3 = new aws.S3({ apiVersion: '2006-03-01' }); | |
exports.handler = function(event, context) { | |
console.log('Received event:', JSON.stringify(event, null, 2)); | |
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 | |
}; | |
if (key.indexOf('-line.png') > -1) { | |
context.done(null, ''); | |
} | |
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 { | |
console.log('CONTENT TYPE:', data.ContentType); | |
var inputPath = "/tmp/input." + (event.outputExtension || 'JPG'); | |
var outputPath = "/tmp/output.png"; | |
require('fs').writeFileSync(inputPath, data.Body); | |
var lineKey = key.split('.')[0] + '-line.png'; | |
gm(inputPath) | |
.fuzz('20%') | |
.trim() | |
.resize(HEIGHT, WIDTH) | |
.extent(HEIGHT, WIDTH) | |
.fuzz('10%') | |
.fill('#00000000') | |
.setDraw('matte', 1, 1, 'floodfill') | |
.setDraw('matte', 1, WIDTH - 1, 'floodfill') | |
.setDraw('matte', HEIGHT - 1, 1, 'floodfill') | |
.setDraw('matte', HEIGHT - 1, WIDTH - 1, 'floodfill') | |
.write(outputPath, function (err) { | |
if (!err) { | |
s3.putObject({ | |
Bucket: bucket, | |
Key: lineKey, | |
Body: new Buffer(fs.readFileSync(outputPath)) | |
}, function(err) { | |
if (err) { | |
console.log(err); | |
context.done('error', 'error s3 put object' + err); | |
} else { | |
context.done(null, ''); | |
} | |
}); | |
} | |
}); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment