forked from yjgaia/hanul-graphicsmagick
-
Notifications
You must be signed in to change notification settings - Fork 0
/
imagemagick.js
517 lines (478 loc) · 15.5 KB
/
imagemagick.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
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
var
childproc = require('child_process'),
//math = require('mathjs'),
EventEmitter = require('events').EventEmitter;
//increased max buffer (crashes on AWS Lambda) 2500x1024
function exec2(file, args /*, options, callback */) {
var options = {
encoding: 'utf8'
, timeout: 0
, maxBuffer: 2500 * 1024
, killSignal: 'SIGKILL'
, output: null
};
var callback = arguments[arguments.length - 1];
if ('function' != typeof callback) callback = null;
if (typeof arguments[2] == 'object') {
var keys = Object.keys(options);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
if (arguments[2][k] !== undefined) options[k] = arguments[2][k];
}
}
var child = childproc.spawn(file, args);
child.on('error', function (err) {
callback(err, "", "");
});
var killed = false;
var timedOut = false;
var Wrapper = function (proc) {
this.proc = proc;
this.stderr = new Accumulator();
proc.emitter = new EventEmitter();
proc.on = proc.emitter.on.bind(proc.emitter);
this.out = proc.emitter.emit.bind(proc.emitter, 'data');
this.err = this.stderr.out.bind(this.stderr);
this.errCurrent = this.stderr.current.bind(this.stderr);
};
Wrapper.prototype.finish = function (err) {
this.proc.emitter.emit('end', err, this.errCurrent());
};
var Accumulator = function (cb) {
this.stdout = {contents: ""};
this.stderr = {contents: ""};
this.callback = cb;
var limitedWrite = function (stream) {
return function (chunk) {
stream.contents += chunk;
if (!killed && stream.contents.length > options.maxBuffer) {
child.kill(options.killSignal);
killed = true;
}
};
};
this.out = limitedWrite(this.stdout);
this.err = limitedWrite(this.stderr);
};
Accumulator.prototype.current = function () {
return this.stdout.contents;
};
Accumulator.prototype.errCurrent = function () {
return this.stderr.contents;
};
Accumulator.prototype.finish = function (err) {
this.callback(err, this.stdout.contents, this.stderr.contents);
};
var std = callback ? new Accumulator(callback) : new Wrapper(child);
var timeoutId;
if (options.timeout > 0) {
timeoutId = setTimeout(function () {
if (!killed) {
child.kill(options.killSignal);
timedOut = true;
killed = true;
timeoutId = null;
}
}, options.timeout);
}
child.stdout.setEncoding(options.encoding);
child.stderr.setEncoding(options.encoding);
child.stdout.addListener("data", function (chunk) {
std.out(chunk, options.encoding);
});
child.stderr.addListener("data", function (chunk) {
std.err(chunk, options.encoding);
});
var version = process.versions.node.split('.');
child.addListener(version[0] == 0 && version[1] < 7 ? "exit" : "close", function (code, signal) {
if (timeoutId) clearTimeout(timeoutId);
if (code === 0 && signal === null) {
std.finish(null);
} else {
var e = new Error("Command " + (timedOut ? "timed out" : "failed") + ": " + std.errCurrent());
e.timedOut = timedOut;
e.killed = killed;
e.code = code;
e.signal = signal;
std.finish(e);
}
});
return child;
};
function parseIdentify(input) {
var lines = input.split("\n"),
prop = {},
props = [prop],
prevIndent = 0,
indents = [indent],
currentLine, comps, indent, compName;
lines.shift(); //drop first line (Image: name.jpg)
for (var i = 0, len = lines.length; i < len; i++) {
currentLine = lines[i];
indent = typeof currentLine.search === 'function' ? indent = currentLine.search(/\S/) : -1;
//indent = currentLine.search(/\S/);
if (indent < prevIndent && indent === 0) {
prop[compName] += currentLine;
} else if (indent >= 0) {
comps = currentLine.split(': ');
if (indent > prevIndent) indents.push(indent);
while (indent < prevIndent && props.length) {
indents.pop();
prop = props.pop();
prevIndent = indents[indents.length - 1];
}
if (comps.length < 2) {
props.push(prop);
prop = prop[currentLine.split(':')[0].trim().toLowerCase()] = {};
} else {
// prop[comps[0].trim().toLowerCase()] = comps[1].trim()
compName = comps[0].trim().toLowerCase();
prop[compName] = comps[1].trim();
}
prevIndent = indent;
}
}
return prop;
};
exports.identify = function (pathOrArgs, callback) {
var isCustom = Array.isArray(pathOrArgs),
isData,
args = isCustom ? ([]).concat(pathOrArgs) : ['-verbose', pathOrArgs];
if (typeof args[args.length - 1] === 'object') {
isData = true;
pathOrArgs = args[args.length - 1];
args[args.length - 1] = '-';
if (!pathOrArgs.data)
throw new Error('first argument is missing the "data" member');
} else if (typeof pathOrArgs === 'function') {
args[args.length - 1] = '-';
callback = pathOrArgs;
}
var proc = exec2(exports.identify.path, args, {timeout: 120000}, function (err, stdout, stderr) {
var result, geometry;
if (!err) {
if (isCustom) {
result = stdout;
} else {
result = parseIdentify(stdout);
if (result['geometry']) {
geometry = result['geometry'].split(/x/);
result.width = parseInt(geometry[0]);
result.height = parseInt(geometry[1]);
}
result.format = result.format.match(/\S*/)[0]
result.width = parseInt(geometry[0]);
result.height = parseInt(geometry[1]);
result.depth = parseInt(result.depth);
if (result.quality !== undefined) result.quality = parseInt(result.quality) / 100;
}
}
callback(err, result);
});
if (isData) {
if ('string' === typeof pathOrArgs.data) {
proc.stdin.setEncoding('binary');
proc.stdin.write(pathOrArgs.data, 'binary');
proc.stdin.end();
} else {
proc.stdin.end(pathOrArgs.data);
}
}
return proc;
};
exports.identify.path = 'identify';
function ExifDate(value) {
// YYYY:MM:DD HH:MM:SS -> Date(YYYY-MM-DD HH:MM:SS +0000)
value = value.split(/ /);
return new Date(value[0].replace(/:/g, '-') + ' ' +
value[1] + ' +0000');
};
function exifKeyName(k) {
return k.replace(exifKeyName.RE, function (x) {
if (x.length === 1) return x.toLowerCase();
else return x.substr(0, x.length - 1).toLowerCase() + x.substr(x.length - 1);
});
};
exifKeyName.RE = /^[A-Z]+/;
var exifFieldConverters = {
// Numbers
bitsPerSample: Number, compression: Number, exifImageLength: Number,
exifImageWidth: Number, exifOffset: Number, exposureProgram: Number,
flash: Number, imageLength: Number, imageWidth: Number, isoSpeedRatings: Number,
jpegInterchangeFormat: Number, jpegInterchangeFormatLength: Number,
lightSource: Number, meteringMode: Number, orientation: Number,
photometricInterpretation: Number, planarConfiguration: Number,
resolutionUnit: Number, rowsPerStrip: Number, samplesPerPixel: Number,
sensingMethod: Number, stripByteCounts: Number, subSecTime: Number,
subSecTimeDigitized: Number, subSecTimeOriginal: Number, customRendered: Number,
exposureMode: Number, focalLengthIn35mmFilm: Number, gainControl: Number,
saturation: Number, sharpness: Number, subjectDistanceRange: Number,
subSecTime: Number, subSecTimeDigitized: Number, subSecTimeOriginal: Number,
whiteBalance: Number, sceneCaptureType: Number,
// Dates
dateTime: ExifDate, dateTimeDigitized: ExifDate, dateTimeOriginal: ExifDate
};
exports.readMetadata = function (path, callback) {
return exports.identify(['-format', '%[EXIF:*]', path], function (err, stdout) {
var meta = {};
if (!err) {
stdout.split(/\n/).forEach(function (line) {
var eq_p = line.indexOf('=');
if (eq_p === -1) return;
var key = line.substr(0, eq_p).replace('/', '-'),
value = line.substr(eq_p + 1).trim(),
typekey = 'default';
var p = key.indexOf(':');
if (p !== -1) {
typekey = key.substr(0, p);
key = key.substr(p + 1);
if (typekey === 'exif') {
key = exifKeyName(key);
var converter = exifFieldConverters[key];
if (converter) value = converter(value);
}
}
if (!(typekey in meta)) meta[typekey] = {key: value};
else meta[typekey][key] = value;
})
}
callback(err, meta);
});
};
exports.convert = function (args, timeout, callback) {
var procopt = {encoding: 'binary'};
if (typeof timeout === 'function') {
callback = timeout;
timeout = 0;
} else if (typeof timeout !== 'number') {
timeout = 0;
}
if (timeout && (timeout = parseInt(timeout)) > 0 && !isNaN(timeout))
procopt.timeout = timeout;
return exec2(exports.convert.path, args, procopt, callback);
};
exports.convert.path = 'convert';
var resizeCall = function (t, callback) {
var proc = exports.convert(t.args, t.opt.timeout, callback);
if (t.opt.srcPath.match(/-$/)) {
if ('string' === typeof t.opt.srcData) {
proc.stdin.setEncoding('binary');
proc.stdin.write(t.opt.srcData, 'binary');
proc.stdin.end();
} else {
proc.stdin.end(t.opt.srcData);
}
}
return proc;
};
var simpleCall = function (t, callback) {
var proc = exports.convert(t.args, 0, callback);
if (t.opt.srcPath.match(/-$/)) {
if ('string' === typeof t.opt.srcData) {
proc.stdin.setEncoding('binary');
proc.stdin.write(t.opt.srcData, 'binary');
proc.stdin.end();
} else {
proc.stdin.end(t.opt.srcData);
}
}
return proc;
};
exports.EXIFAutoRotate = function (options, callback) {
var default_options = {
srcPath: null,
dstPath: null,
srcData: null
};
var _args = [];
if (options.srcPath) {
_args.push(options.srcPath);
}
_args.push("-auto-orient");
if (options.dstPath) {
_args.push(options.dstPath);
}
return simpleCall({args: _args, opt: options}, callback)
};
exports.resize = function (options, callback) {
var t = exports.resizeArgs(options);
return resizeCall(t, callback)
};
exports.crop = function (options, callback) {
if (typeof options !== 'object')
throw new TypeError('First argument must be an object');
if (!options.srcPath && !options.srcData)
throw new TypeError("No srcPath or data defined");
if (!options.height && !options.width)
throw new TypeError("No width or height defined");
if (options.srcPath) {
var args = options.srcPath;
} else {
var args = {
data: options.srcData
};
}
exports.identify(args, function (err, meta) {
if (err) return callback && callback(err);
var t = exports.resizeArgs(options),
ignoreArg = false,
printNext = false,
args = [];
t.args.forEach(function (arg) {
if (printNext === true) {
console.log("arg", arg);
printNext = false;
}
// ignoreArg is set when resize flag was found
if (!ignoreArg && (arg != '-resize'))
args.push(arg);
// found resize flag! ignore the next argument
if (arg == '-resize') {
console.log("resize arg");
ignoreArg = true;
printNext = true;
}
if (arg === "-crop") {
console.log("crop arg");
printNext = true;
}
// found the argument after the resize flag; ignore it and set crop options
if ((arg != "-resize") && ignoreArg) {
var dSrc = meta.width / meta.height,
dDst = t.opt.width / t.opt.height,
resizeTo = (dSrc < dDst) ? '' + t.opt.width + 'x' : 'x' + t.opt.height,
dGravity = options.gravity ? options.gravity : "Center";
args = args.concat([
'-resize', resizeTo,
'-gravity', dGravity,
'-crop', '' + t.opt.width + 'x' + t.opt.height + '+0+0',
'+repage'
]);
ignoreArg = false;
}
});
t.args = args;
resizeCall(t, callback);
})
};
var maxDimension = function (width, height, operator) {
var args = [], operation = "";
var resize_size = Math.max(width, height);
if (operator == 1) {
operation = "\!";
} else if (operator == 2) {
operation = "\>";
} else if (operator == 3) {
operation = "<";
} else if (operator == 4) {
operation = "^";
} else if (operator == 0) {
} else {
console.log("im", "operation is out of range.");
}
args.push(String(resize_size) + 'x' + String(resize_size) + operation);
return args;
};
exports.resizeArgs = function (options) {
var opt = {
srcPath: null,
srcData: null,
srcFormat: null,
dstPath: null,
quality: 0.8,
format: 'jpg',
progressive: false,
colorspace: null,
width: 0,
height: 0,
percent: 0.0,
area_total_pixels: 0,
resize_operation: 0,
strip: true,
filter: 'Lagrange',
sharpening: 0.2,
customArgs: [],
timeout: 0,
debug: false
};
// check options
if (typeof options !== 'object')
throw new Error('first argument must be an object');
for (var k in opt) if (k in options) opt[k] = options[k];
if (!opt.srcPath && !opt.srcData)
throw new Error('both srcPath and srcData are empty');
// normalize options
if (!opt.format) opt.format = 'jpg';
if (!opt.srcPath) {
opt.srcPath = (opt.srcFormat ? opt.srcFormat + ':-' : '-'); // stdin
}
if (!opt.dstPath) {
opt.dstPath = (opt.format ? opt.format + ':-' : '-');
}// stdout
if (opt.width === 0 && opt.height === 0) {
throw new Error('both width and height can not be 0 (zero)');
}
// build args
var args = [opt.srcPath];
if (opt.sharpening > 0) {
args = args.concat([
'-set', 'option:filter:blur', String(1.0 - opt.sharpening)]);
}
if (opt.filter) {
args.push('-filter');
args.push(opt.filter);
}
if (opt.strip) {
args.push('-strip');
}
if (opt.format === 'gif') {
args.push('-coalesce');
}
var has_dimension_size = opt.width > 0 || opt.height > 0;
var has_percent = opt.percent > 0.0;
var has_area_pixels = opt.area_total_pixels > 0;
if (opt.resize_operation < 5 && has_dimension_size) {
args.push('-resize');
var args_operation = maxDimension(opt.width, opt.height, opt.resize_operation);
args = args.concat(args_operation);
}
if (opt.resize_operation === 5 && has_percent) {
args.push('-resize');
args.push(String(opt.percent) + '%');
}
if (opt.resize_operation === 6 && has_area_pixels) {
/**
Resize using a Pixel Area Count Limit ('@' flag)
There is one final "-resize" option flag. The "at" symbol '@', will resize an image to contain no more than the given number of pixels. This can be used for example to make a collection of images of all different sizes roughly the same size. For example here we resize both our images to a rough 64x64 size, or 4096 pixels in size.
*/
args.push('-resize');
args.push(String(opt.area_total_pixels) + '@');
}
if (opt.resize_operation === 7 && has_dimension_size) {
}
opt.format = opt.format.toLowerCase();
var isJPEG = (opt.format === 'jpg' || opt.format === 'jpeg');
if (isJPEG && opt.progressive) {
args.push('-interlace');
args.push('plane');
}
if (isJPEG || opt.format === 'png') {
args.push('-quality');
args.push(Math.round(opt.quality * 100.0).toString());
}
else if (opt.format === 'miff' || opt.format === 'mif') {
args.push('-quality');
args.push(Math.round(opt.quality * 9.0).toString());
}
if (opt.colorspace) {
args.push('-colorspace');
args.push(opt.colorspace);
}
if (Array.isArray(opt.customArgs) && opt.customArgs.length)
args = args.concat(opt.customArgs);
args.push(opt.dstPath);
if (opt.debug) {
console.log("==> im:: debug for final command :: ", args);
}
return {opt: opt, args: args};
};