forked from trinketapp/aws-lambda-create-thumbnail
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexports.js
92 lines (84 loc) · 2.54 KB
/
exports.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// dependencies
var async = require('async')
var AWS = require('aws-sdk')
var gm = require('gm').subClass({ imageMagick: true }) // Enable ImageMagick integration.
// constants
var MAX_WIDTH = 100
var MAX_HEIGHT = 100
// get reference to S3 client
var s3 = new AWS.S3()
exports.handler = function (event, context) {
// Read options from the event.
var srcBucket = event.Records[0].s3.bucket.name
var srcKey = event.Records[0].s3.object.key
var dstBucket = srcBucket + '-thumb'
var dstKey = srcKey
// Sanity check: validate that source and destination are different buckets.
if (srcBucket === dstBucket) {
console.error('Destination bucket must not match source bucket.')
return
}
// Infer the image type.
var typeMatch = srcKey.match(/\.([^.]*)$/)
if (!typeMatch) {
console.error('unable to infer image type for key ' + srcKey)
return
}
var validImageTypes = ['png', 'jpg', 'jpeg', 'gif']
var imageType = typeMatch[1]
if (validImageTypes.indexOf(imageType.toLowerCase()) < 0) {
return
}
// Download the image from S3, transform, and upload to a different S3 bucket.
async.waterfall([
function download (next) {
// Download the image from S3 into a buffer.
s3.getObject({
Bucket: srcBucket,
Key: srcKey
}, next)
},
function tranform (response, next) {
gm(response.Body).size(function (err, size) {
// Infer the scaling factor to avoid stretching the image unnaturally.
var scalingFactor = Math.min(
MAX_WIDTH / size.width,
MAX_HEIGHT / size.height
)
var width = scalingFactor * size.width
var height = scalingFactor * size.height
// Transform the image buffer in memory.
this.resize(width, height)
.toBuffer(imageType, function (err, buffer) {
if (err) {
next(err)
} else {
next(null, response.ContentType, buffer)
}
})
})
},
function upload (contentType, data, next) {
// Stream the transformed image to a different S3 bucket.
s3.putObject({
Bucket: dstBucket,
Key: dstKey,
Body: data,
ContentType: contentType,
ACL: 'public-read'
}, next)
}],
function (err) {
if (err) {
console.error(
'Unable to resize ' + srcBucket + '/' + srcKey +
' and upload to ' + dstBucket + '/' + dstKey +
' due to an error: ' + err
)
context.done()
} else {
context.done()
}
}
)
}