forked from jwagner/smartcrop-sharp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
64 lines (59 loc) · 1.72 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
var smartcrop = require('smartcrop');
var sharp = require('sharp');
function rgb2rgba(input) {
var output = new Buffer(input.length / 3 * 4);
for (var i = 0; i < input.length;i += 3) {
output[i / 3 * 4] = input[i];
output[i / 3 * 4 + 1] = input[i + 1];
output[i / 3 * 4 + 2] = input[i + 2];
output[i / 3 * 4 + 3] = 255;
}
return output;
}
var iop = {
open: function(src) {
var image = sharp(src);
return image.metadata().then(function(metadata) {
return {
width: metadata.width,
height: metadata.height,
_sharp: image,
};
});
},
resample: function(image, width, height) {
// this does not clone the image, better performance but fragile
// (depends on the assumtion that resample+getData is only called once per img)
return new Promise(function(resolve, reject) {
resolve({
width: ~~width,
height: ~~height,
_sharp: image._sharp,
});
});
},
getData: function(image) {
return image._sharp
.resize(image.width, image.height)
.raw()
.toBuffer()
.then(function(data) {
if (data.length === image.width * image.height * 3) {
data = rgb2rgba(data);
}
if (data.length !== image.width * image.height * 4) {
console.log(image.width, image.height);
throw new Error('unexpected data length ' + data.length);
}
return new smartcrop.ImgData(image.width, image.height, data);
});
},
};
exports.crop = function(img, options, callback) {
options = options || {};
options.imageOperations = iop;
return smartcrop.crop(img, options, callback);
};
// exports.crop('kitty.jpg').then(function() {
// console.log(arguments);
// });