forked from jpsim/AWSPics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
96 lines (88 loc) · 2.63 KB
/
index.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
93
94
95
96
var async = require("async");
var AWS = require("aws-sdk");
var im = require("gm").subClass({imageMagick: true});
var s3 = new AWS.S3({signatureVersion: 'v4'});
const DEFAULT_PICS_ORIGINAL_PATH = 'pics/original/';
function getPicsOriginalPath() {
return process.env.PICS_ORIGINAL_PATH || DEFAULT_PICS_ORIGINAL_PATH;
}
function getImageType(objectContentType) {
if (objectContentType === "image/jpeg") {
return "jpeg";
} else if (objectContentType === "image/png") {
return "png";
} else {
throw new Error("unsupported objectContentType " + objectContentType);
}
}
function cross(left, right) {
var res = [];
left.forEach(function(l) {
right.forEach(function(r) {
res.push([l, r]);
});
});
return res;
}
exports.handler = function(event, context) {
console.log("event ", JSON.stringify(event));
async.mapLimit(event.Records, 4, function(record, cb) {
var originalKey = decodeURIComponent(record.s3.object.key.replace(/\+/g, " "));
s3.getObject({
"Bucket": record.s3.bucket.name,
"Key": originalKey
}, function(err, data) {
if (err) {
cb(err);
} else {
cb(null, {
"originalKey": originalKey,
"contentType": data.ContentType,
"imageType": getImageType(data.ContentType),
"buffer": data.Body,
"record": record
});
}
});
}, function(err, images) {
if (err) {
context.fail(err);
} else {
var resizePairs = cross(["1200x750", "360x225"], images);
async.eachLimit(resizePairs, 4, function(resizePair, cb) {
var config = resizePair[0];
var image = resizePair[1];
var width = config.split('x')[0]
var height = config.split('x')[1]
var operation = im(image.buffer).autoOrient().resize(width, height, '^');
if (config == "360x225") {
operation = operation.gravity('Center').crop(width, height);
}
operation.toBuffer(image.imageType, function(err, buffer) {
if (err) {
cb(err);
} else {
s3.putObject({
"Bucket": process.env.RESIZED_BUCKET,
"Key": (
"pics/resized/" + config + "/" +
image.originalKey.replace(getPicsOriginalPath(), "")
),
"Body": buffer,
"ServerSideEncryption": "AES256",
"ContentType": image.contentType
}, function(err) {
cb(err);
});
}
});
}, function(err) {
if (err) {
context.fail(err);
} else {
context.succeed();
}
});
}
});
};