-
Notifications
You must be signed in to change notification settings - Fork 219
/
ImageResizer.js
74 lines (65 loc) · 2.12 KB
/
ImageResizer.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
"use strict";
const ImageData = require("./ImageData");
const gm = require("gm").subClass({ imageMagick: true });
const cropSpec = /(\d+)x(\d+)([+-]\d+)?([+-]\d+)?(%)?/;
class ImageResizer {
/**
* Image Resizer
* resize image with ImageMagick
*
* @constructor
* @param Object options
*/
constructor(options) {
this.options = options;
}
/**
* Execute resize
*
* @public
* @param ImageData image
* @return Promise
*/
exec(image) {
const acl = this.options.acl;
return new Promise((resolve, reject) => {
console.log("Resizing to: " + (this.options.directory || "in-place"));
let img = gm(image.data).geometry(this.options.size.toString());
if ( "orientation" in this.options ) {
img = img.autoOrient();
}
if ( "gravity" in this.options ) {
img = img.gravity(this.options.gravity);
}
if ( "background" in this.options ) {
img = img.background(this.options.background).flatten();
}
if ( "crop" in this.options ) {
const cropArgs = this.options.crop.match(cropSpec);
const cropWidth = cropArgs[1];
const cropHeight = cropArgs[2];
const cropX = cropArgs[3];
const cropY = cropArgs[4];
const cropPercent = cropArgs[5];
img = img.crop(cropWidth, cropHeight, cropX, cropY, cropPercent === "%");
}
if( "format" in this.options ) {
img = img.setFormat(this.options.format);
}
img.toBuffer((err, buffer) => {
if (err) {
reject(err);
} else {
resolve(new ImageData(
image.fileName,
image.bucketName,
buffer,
image.headers,
acl || image.acl
));
}
});
});
}
}
module.exports = ImageResizer;