forked from iron-io/functions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.js
70 lines (62 loc) · 1.59 KB
/
example.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
var im = require('imagemagick');
var fs = require('fs');
var AWS = require('aws-sdk');
// cb(err, resized) is called with true if resized.
function resizeIfRequired(err, features, fileSrc, fileDst, cb) {
if (err) {
cb(err, false);
return;
}
var targetWidth = 1024;
if (features.width > targetWidth)
{
im.resize({
srcPath : fileSrc,
dstPath : fileDst,
width : targetWidth,
format: 'jpg'
}, function(err) {
if (err) {
cb(err, false);
} else {
cb(null, true);
}
});
} else {
cb(null, false);
}
}
exports.run = function(event, context) {
var bucketName = event['bucket']
var srcImageKey = event['srcKey']
var dstImageKey = event['dstKey']
var s3 = new AWS.S3();
s3.getObject({
Bucket: bucketName,
Key: srcImageKey
}, function (err, data) {
if (err) throw err;
var fileSrc = '/tmp/image-src.dat';
var fileDst = '/tmp/image-dst.dat'
fs.writeFileSync(fileSrc, data.Body)
im.identify(fileSrc, function(err, features) {
resizeIfRequired(err, features, fileSrc, fileDst, function(err, resized) {
if (err) throw err;
if (resized) {
s3.putObject({
Bucket:bucketName,
Key: dstImageKey,
Body: fs.createReadStream(fileDst),
ContentType: 'image/jpeg',
ACL: 'public-read',
}, function (err, data) {
if (err) throw err;
context.succeed("Image updated");
});
} else {
context.succeed("Image not updated");
}
});
});
});
}