forked from hacksparrow/node-easyimage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheasyimage.js
More file actions
324 lines (256 loc) · 7.73 KB
/
Copy patheasyimage.js
File metadata and controls
324 lines (256 loc) · 7.73 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
var Q = require('q');
var exec = require('child_process').execFile;
var command = require('child_process').exec;
var path = require('path');
var fs = require('fs');
var mkdirp = require('mkdirp');
var BINARY_NAME = "gm";
// check if GraphicsMagick is available on the system
command((BINARY_NAME + ' convert -version'), function(err, stdout, stderr) {
// GraphicsMagick is NOT available on the system, exit with download info
if (err) {
console.log(' GraphicsMagick Not Found'.red)
console.log(' EasyImage requires GraphicsMagick to work. Install it from http://www.graphicsmagick.org/\n')
}
})
var error_messages = {
'path': 'Missing image paths.\nMake sure both source and destination files are specified.',
'dim': 'Missing dimensions.\nSpecify the width atleast.',
'restricted': 'The command you are trying to execute is prohibited.',
'unsupported': 'File not supported.',
};
// execute a child process with a timeout
function exec_with_timeout(action, args, timeout, callback) {
timeout = (timeout || 10000);
var execTimeout = null;
var child = exec(BINARY_NAME, [action].concat(args), function(err, stdout, stderr) {
if (execTimeout !== null) {
clearTimeout(execTimeout);
execTimeout = null;
}
callback(err, stdout, stderr);
});
execTimeout = setTimeout(function() {
execTimeout = null;
// child process took too much time, kill it now
child.kill("SIGKILL");
}, timeout);
}
// general info function
function info(file) {
var deferred = Q.defer();
var parseSize = function(sizeString) {
var unit = {
i: 1,
Ki: 1000,
Mi: 1000000, // =1000^2
Gi: 1000000000, // =1000^3
Ti: 1000000000000 // =1000^4
};
var rx = /^(\d*\.?\d*)([KMGT]?i)$/; // regex for extract the float value and its unit
var sizeArray = rx.exec(sizeString);
if (sizeArray) {
return parseFloat(sizeArray[1]) * unit[sizeArray[2]];
}
return -1;
};
// %q = depth, %m = type, %w = width, %h = height, %b = rounded filesize in byte, %f = filename, %x = density
var args = ['-format']
args.push('%m %q %w %h %b %x %y %f')
args.push(file)
exec_with_timeout('identify', args, undefined, function(err, stdout, stderr) {
var info = {};
//console.log(stdout)
//Basic error handling
if (stdout) {
var temp = stdout.replace(/PixelsPerInch/g, '').replace(/PixelsPerCentimeter/g, '').replace(/Undefined/g, '').split(/\s+/g);
//Basic error handling:
if (temp.length < 7) {
deferred.reject(new Error(stderr || error_messages['unsupported']));
} else {
info.type = temp[0].toLowerCase();
info.depth = parseInt(temp[1]);
info.width = parseInt(temp[2]);
info.height = parseInt(temp[3]);
info.size = parseSize(temp[4]);
info.density = {
x: parseFloat(temp[5]),
y: parseFloat(temp[6]),
};
info.name = temp.slice(7).join(' ').replace(/(\r\n|\n|\r)/gm, '').trim();
info.path = file;
if (stderr) {
info.warnings = stderr.split('\n');
}
deferred.resolve(info);
}
} else {
deferred.reject(new Error(stderr || error_messages['unsupported']));
}
});
return deferred.promise;
}
// get basic information about an image file
exports.info = function(file) {
return info(file);
};
function directoryCheck(options, success, failure) {
var dstPath = options.dst;
// clear format from path (if any set)
if (dstPath.includes(":")) {
dstPath = dstPath.split(":")[1];
}
var targetDir = path.dirname(dstPath);
fs.exists(targetDir, function (exists) {
if (exists) {
success()
}
else {
mkdirp(targetDir, function (error) {
if (error) {
failure(error)
}
else {
success()
}
})
}
})
}
// resize an image
exports.resize = function(options) {
var deferred = Q.defer();
function imgResize() {
if (options.src === undefined || options.dst === undefined) return deferred.reject(error_messages['path']);
if (options.width === undefined) return deferred.reject(error_messages['dim']);
options.height = options.height || options.width;
var args = [options.src]
if (options.srcWidth && options.srcHeight) {
args.push('-size')
args.push(options.srcWidth + 'x' + options.srcHeight)
}
if (options.flatten) {
args.push('-flatten')
if (options.background) {
args.push('-background')
args.push(options.background)
}
}
else {
if (options.background) {
args.push('-background')
args.push(options.background)
args.push('-flatten')
}
}
if (options.autoOrient) {
args.push('-auto-orient')
}
if (options.strip) {
args.push('-strip')
}
args.push('-resize')
args.push(options.width + 'x' + options.height)
if (options.neverEnlarge) {
args[args.length-1] += '>';
}
if (options.ignoreAspectRatio) {
args[args.length-1] += '!';
}
if (options.quality) {
args.push('-quality')
args.push(options.quality)
}
if (options.background) {
args.push('-background')
args.push(options.background)
}
if (options.interlace) {
args.push('-interlace')
args.push(options.interlace)
}
args.push(options.dst)
exec_with_timeout('convert', args, options.timeout, function(err, stdout, stderr) {
if (err) deferred.reject(err);
deferred.resolve(options.dst);
});
}
directoryCheck(options, imgResize, deferred.reject)
return deferred.promise;
};
// create thumbnails
exports.thumbnail = function(options) {
var deferred = Q.defer();
function imgThumbnail() {
if (options.src === undefined || options.dst === undefined) return deferred.reject(error_messages['path']);
if (options.width === undefined) return deferred.reject(error_messages['dim']);
options.height = options.height || options.width;
options.gravity = options.gravity || 'Center';
options.x = options.x || 0;
options.y = options.y || 0;
info(options.src).then(function(original) {
// dimensions come as strings, convert them to number
original.width = +original.width;
original.height = +original.height;
var resizewidth = options.width;
var resizeheight = options.height;
if (original.width > original.height) { resizewidth = ''; }
else if (original.height > original.width) { resizeheight = ''; }
var args = [options.src]
if (options.flatten) {
args.push('-flatten')
if (options.background) {
args.push('-background')
args.push(options.background)
}
}
else {
if (options.background) {
args.push('-background')
args.push(options.background)
args.push('-flatten')
}
}
if (options.autoOrient) {
args.push('-auto-orient')
}
args.push('-gravity')
args.push(options.gravity)
args.push('-strip')
args.push('-thumbnail')
args.push(resizewidth + 'x' + resizeheight)
args.push('-crop')
args.push(options.width + 'x'+ options.height + '+' + options.x + '+' + options.y)
if (options.quality) {
args.push('-quality')
args.push(options.quality)
}
if (options.background) {
args.push('-background')
args.push(options.background)
}
if (options.interlace) {
args.push('-interlace')
args.push(options.interlace)
}
args.push(options.dst)
exec_with_timeout('convert', args, options.timeout, function(err, stdout, stderr) {
if (err) return deferred.reject(err);
deferred.resolve(options.dst);
});
}, function (err) { deferred.reject(err); });
}
directoryCheck(options, imgThumbnail, deferred.reject)
return deferred.promise;
};
// issue your own GraphicsMagick command
exports.exec = function(cmd) {
var deferred = Q.defer();
process.nextTick(function () {
command((BINARY_NAME + " " + cmd), function(err, stdout, stderr) {
if (err) return deferred.reject(err);
deferred.resolve(stdout);
});
})
return deferred.promise;
};