forked from jimp-dev/jimp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
executable file
·2830 lines (2440 loc) · 101 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
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var FS = require("fs");
var PNG = require("pngjs").PNG;
var JPEG = require("jpeg-js");
var BMP = require("bmp-js");
var GIF = require("./omggif.js");
var UTIF = require("utif");
var MIME = require("mime");
var TinyColor = require("tinycolor2");
var Resize = require("./resize.js");
var Resize2 = require("./resize2.js");
var RawBody = require("raw-body");
var FileType = require("file-type");
var PixelMatch = require("pixelmatch");
var EXIFParser = require("exif-parser");
var ImagePHash = require("./phash.js");
var BigNumber = require('bignumber.js');
var BMFont = require("load-bmfont");
var Path = require("path");
var MkDirP = require("mkdirp");
var Request = require("./src/request");
var EventEmitter = require('events');
// polyfill Promise for Node < 0.12
var Promise = global.Promise || require('es6-promise').Promise;
var isDef = (v)=> typeof v !== "undefined" && v !== null;
// logging methods
var chars = 0;
function log (msg) {
clear();
if (typeof process !== 'undefined' && process && process.stdout)
process.stdout.write(msg);
else if (typeof console !== 'undefined' && console)
console.log('Jimp', msg);
chars = msg.length;
}
function clear () {
if (process && process.stdout)
while (chars-- > 0)
process.stdout.write("\b");
}
process.on("exit", clear);
// no operation
function noop () {}
// error checking methods
function isNodePattern (cb) {
if (typeof cb === "undefined") return false;
if (typeof cb !== "function")
throw new Error("Callback must be a function");
return true;
}
function throwError (error, cb) {
if (typeof error === "string") error = new Error(error);
if (typeof cb === "function") return cb.call(this, error);
else throw error;
}
function isArrayBuffer (test) {
return Object.prototype.toString.call(test).toLowerCase().indexOf("arraybuffer") > -1;
}
// Prepare a Buffer object from the arrayBuffer. Necessary in the browser > node conversion,
// But this function is not useful when running in node directly
function bufferFromArrayBuffer (arrayBuffer) {
var buffer = new Buffer(arrayBuffer.byteLength);
var view = new Uint8Array(arrayBuffer);
for (var i = 0; i < buffer.length; ++i) {
buffer[i] = view[i];
}
return buffer;
}
function loadBufferFromPath (src, cb) {
if (FS && typeof FS.readFile === "function" && !src.match(/^(http|ftp)s?:\/\/./)) {
FS.readFile(src, cb);
} else {
Request(src, function (err, response, data) {
if (err) return cb(err);
if (typeof data === "object" && Buffer.isBuffer(data)) {
return cb(null, data);
} else {
let msg = "Could not load Buffer from <" + src + "> " +
"(HTTP: " + response.statusCode + ")";
return Error(msg);
}
});
}
}
/**
* Helper to create Jimp methods that emit events before and after its execution.
* @param methodName The name to be appended to Jimp prototype.
* @param evName The event name to be called.
* It will be prefixed by `before-` and emited when on method call.
* It will be appended by `ed` and emited after the method run.
* @param method A function implementing the method itself.
* It will also create a quiet version that will not emit events, to not
* mess the user code with many `changed` event calls. You can call with
* `methodName + "Quiet"`.
*
* The emited event comes with a object parameter to the listener with the
* `methodName` as one attribute.
*/
function JimpEvMethod (methodName, evName, method) {
var evNameBefore = "before-"+evName;
var evNameAfter = evName.replace(/e$/, "") + "ed";
Jimp.prototype[methodName] = function () {
var wrapedCb, cb = arguments[method.length-1];
var that = this;
if (typeof cb === "function") {
wrapedCb = function (err, data) {
if (err) {
that.emitError(methodName, err);
} else {
that.emitMulti(methodName, evNameAfter, {[methodName]: data});
}
cb.apply(this, arguments);
};
arguments[arguments.length-1] = wrapedCb;
} else {
wrapedCb = false;
}
this.emitMulti(methodName, evNameBefore);
try {
var result = method.apply(this, arguments);
if (!wrapedCb) this.emitMulti(methodName, evNameAfter, {[methodName]: result});
} catch (err) {
err.methodName = methodName;
this.emitError(methodName, err);
}
return result;
}
Jimp.prototype[methodName+"Quiet"] = method;
}
/**
* Simplify JimpEvMethod call for the common `change` evName.
*/
function JimpEvChange (methodName, method) {
JimpEvMethod(methodName, "change", method);
}
/**
* Jimp constructor (from a file)
* @param path a path to the image
* @param (optional) cb a function to call when the image is parsed to a bitmap
*/
/**
* Jimp constructor (from another Jimp image)
* @param image a Jimp image to clone
* @param cb a function to call when the image is parsed to a bitmap
*/
/**
* Jimp constructor (from a Buffer)
* @param data a Buffer containing the image data
* @param cb a function to call when the image is parsed to a bitmap
*/
/**
* Jimp constructor (to generate a new image)
* @param w the width of the image
* @param h the height of the image
* @param (optional) cb a function to call when the image is parsed to a bitmap
*/
class Jimp extends EventEmitter {
constructor () {
super();
var cb = noop;
var that = this;
if (isArrayBuffer(arguments[0]))
arguments[0] = bufferFromArrayBuffer(arguments[0]);
function finish (err, ...args) {
var evData = err || {};
evData.methodName = "constructor";
setTimeout(()=> { // run on next tick.
if (err) that.emitError("constructor", err);
else that.emitMulti("constructor", "initialized");
cb.call(that, ...arguments);
}, 1);
}
if (typeof arguments[0] === "number" && typeof arguments[1] === "number") {
// create a new image
var w = arguments[0];
var h = arguments[1];
cb = arguments[2];
if (typeof arguments[2] === "number") {
this._background = arguments[2];
cb = arguments[3];
}
if (typeof cb === "undefined") cb = noop;
if (typeof cb !== "function")
return throwError.call(this, "cb must be a function", finish);
this.bitmap = {
data: new Buffer(w * h * 4),
width: w,
height: h
};
for (let i = 0; i < this.bitmap.data.length; i+=4) {
this.bitmap.data.writeUInt32BE(this._background, i);
}
finish(null, this);
} else if (arguments[0] instanceof Jimp) {
// clone an existing Jimp
var original = arguments[0];
cb = arguments[1];
if (typeof cb === "undefined") cb = noop;
if (typeof cb !== "function")
return throwError.call(this, "cb must be a function", finish);
var bitmap = new Buffer(original.bitmap.data.length);
original.scanQuiet(0, 0, original.bitmap.width, original.bitmap.height, function (x, y, idx) {
var data = original.bitmap.data.readUInt32BE(idx);
bitmap.writeUInt32BE(data, idx);
});
this.bitmap = {
data: bitmap,
width: original.bitmap.width,
height: original.bitmap.height
};
this._quality = original._quality;
this._deflateLevel = original._deflateLevel;
this._deflateStrategy = original._deflateStrategy;
this._filterType = original._filterType;
this._rgba = original._rgba;
this._background = original._background;
finish(null, this);
} else if (typeof arguments[0] === "string") {
// read from a path
var path = arguments[0];
cb = arguments[1];
if (typeof cb === "undefined") cb = noop;
if (typeof cb !== "function")
return throwError.call(this, "cb must be a function", finish);
loadBufferFromPath(path, function (err, data) {
if (err) return throwError.call(that, err, finish);
parseBitmap.call(that, data, path, finish);
});
} else if (typeof arguments[0] === "object" && Buffer.isBuffer(arguments[0])) {
// read from a buffer
var data = arguments[0];
cb = arguments[1];
if (typeof cb !== "function")
return throwError.call(this, "cb must be a function", finish);
parseBitmap.call(this, data, null, finish);
} else {
// Allow client libs to add new ways to build a Jimp object.
// Extra constructors must be added by `Jimp.appendConstructorOption()`
cb = arguments[arguments.length-1];
if (typeof cb !== "function") {
cb = arguments[arguments.length-2]; // TODO: try to solve the args after cb problem.
if (typeof cb !== "function") cb = function () {};
}
var extraConstructor = Jimp.__extraConstructors.find((c)=> c.test(...arguments));
if (extraConstructor)
new Promise(
(resolve, reject)=> extraConstructor.run.call(this, resolve, reject, ...arguments)
)
.then(()=> finish(null, this))
.catch(finish);
else return throwError.call(this,
"No matching constructor overloading was found. " +
"Please see the docs for how to call the Jimp constructor.", finish
);
}
}
}
Jimp.__extraConstructors = [];
/**
* Allow client libs to add new ways to build a Jimp object.
* @param name identify the extra constructor.
* @param test a function that returns true when it accepts the arguments passed to the main constructor.
* @param runner where the magic happens.
*/
Jimp.appendConstructorOption = function (name, test, runner) {
Jimp.__extraConstructors.push({ name: name, test: test, run: runner });
}
/**
* Emit for multiple listeners
*/
Jimp.prototype.emitMulti = function emitMulti (methodName, eventName, data={}) {
data = Object.assign(data, {methodName, eventName});
this.emit("any", data);
if (methodName) this.emit(methodName, data);
this.emit(eventName, data);
};
Jimp.prototype.emitError = function emitError (methodName, err) {
this.emitMulti(methodName, "error", err);
};
/**
* Read an image from a file or a Buffer
* @param src the path to the file or a Buffer containing the file data
* @retuns a promise
*/
Jimp.read = function (src) {
return new Promise(function (resolve, reject) {
new Jimp(src, (err, image)=> {
if (err) reject(err);
else resolve(image);
});
});
}
// MIME type methods
function getMIMEFromBuffer (buffer, path) {
var fileTypeFromBuffer = FileType(buffer);
if (fileTypeFromBuffer) {
// If FileType returns something for buffer, then return the mime given
return fileTypeFromBuffer.mime;
} else if (path) {
// If a path is supplied, and FileType yields no results, then retry with MIME
// Path can be either a file path or a url
return MIME.lookup(path)
} else {
return null;
}
}
// gets image data from a GIF buffer
function getBitmapFromGIF (data) {
var gifObj = new GIF.GifReader(data);
var gifData = new Buffer(gifObj.width * gifObj.height * 4);
gifObj.decodeAndBlitFrameRGBA(0, gifData);
return {
data: gifData,
width: gifObj.width,
height: gifObj.height
};
}
// parses a bitmap from the constructor to the JIMP bitmap property
function parseBitmap (data, path, cb) {
var that = this;
var mime = getMIMEFromBuffer(data, path);
if (typeof mime !== "string")
return cb(Error("Could not find MIME for Buffer <" + path + ">"));
this._originalMime = mime.toLowerCase();
switch (this.getMIME()) {
case Jimp.MIME_PNG:
var png = new PNG();
png.parse(data, function (err, data) {
if (err) return throwError.call(that, err, cb);
that.bitmap = {
data: new Buffer(data.data),
width: data.width,
height: data.height
};
return cb.call(that, null, that);
});
break;
case Jimp.MIME_JPEG:
try {
this.bitmap = JPEG.decode(data);
try {
this._exif = EXIFParser.create(data).parse();
exifRotate(this); // EXIF data
} catch (err) {
/* meh */
}
return cb.call(this, null, this);
} catch (err) {
return cb.call(this, err, this);
}
case Jimp.MIME_TIFF:
var tiff = (UTIF.decode(data)[0]);
this.bitmap = {
data: new Buffer(tiff.data),
width: tiff.width,
height: tiff.height
};
return cb.call(this, null, this);
case Jimp.MIME_BMP:
case Jimp.MIME_X_MS_BMP:
this.bitmap = BMP.decode(data);
return cb.call(this, null, this);
case Jimp.MIME_GIF:
this.bitmap = getBitmapFromGIF(data);
return cb.call(this, null, this);
default:
return throwError.call(this, "Unsupported MIME type: " + mime, cb);
}
}
/*
* Automagically rotates an image based on its EXIF data (if present)
* @param img a Jimp object
*/
function exifRotate (img) {
var exif = img._exif;
if (exif && exif.tags && exif.tags.Orientation) {
switch (img._exif.tags.Orientation) {
case 1: // Horizontal (normal)
// do nothing
break;
case 2: // Mirror horizontal
img.mirror(true, false);
break;
case 3: // Rotate 180
img.rotate(180, false);
break;
case 4: // Mirror vertical
img.mirror(false, true);
break;
case 5: // Mirror horizontal and rotate 270 CW
img.rotate(-90, false).mirror(true, false);
break;
case 6: // Rotate 90 CW
img.rotate(-90, false);
break;
case 7: // Mirror horizontal and rotate 90 CW
img.rotate(90, false).mirror(true, false);
break;
case 8: // Rotate 270 CW
img.rotate(-270, false);
break;
}
}
return img;
}
// used to auto resizing etc.
Jimp.AUTO = -1;
// supported mime types
Jimp.MIME_PNG = "image/png";
Jimp.MIME_TIFF = "image/tiff";
Jimp.MIME_JPEG = "image/jpeg";
Jimp.MIME_JGD = "image/jgd";
Jimp.MIME_BMP = "image/bmp";
Jimp.MIME_X_MS_BMP = "image/x-ms-bmp";
Jimp.MIME_GIF = "image/gif";
// PNG filter types
Jimp.PNG_FILTER_AUTO = -1;
Jimp.PNG_FILTER_NONE = 0;
Jimp.PNG_FILTER_SUB = 1;
Jimp.PNG_FILTER_UP = 2;
Jimp.PNG_FILTER_AVERAGE = 3;
Jimp.PNG_FILTER_PAETH = 4;
Jimp.RESIZE_NEAREST_NEIGHBOR = 'nearestNeighbor';
Jimp.RESIZE_BILINEAR = 'bilinearInterpolation';
Jimp.RESIZE_BICUBIC = 'bicubicInterpolation';
Jimp.RESIZE_HERMITE = 'hermiteInterpolation';
Jimp.RESIZE_BEZIER = 'bezierInterpolation';
// Align modes for cover, contain, bit masks
Jimp.HORIZONTAL_ALIGN_LEFT = 1;
Jimp.HORIZONTAL_ALIGN_CENTER = 2;
Jimp.HORIZONTAL_ALIGN_RIGHT = 4;
Jimp.VERTICAL_ALIGN_TOP = 8;
Jimp.VERTICAL_ALIGN_MIDDLE = 16;
Jimp.VERTICAL_ALIGN_BOTTOM = 32;
// Discover Jimp directory in any environment. (also in fucking karma)
function getJimpDir () {
var err = Error();
var callLine = err.stack.split(/\n/).filter((l)=> l.match(/getJimpDir/))[0];
var reWebKit = /.*\(([^?]+\/)[^/]+\).*/;
var reMoz = /.*@([^?]+\/).*/;
if (reWebKit.test(callLine)) return callLine.replace(reWebKit, '$1');
else if (reMoz.test(callLine)) return callLine.replace(reMoz, '$1');
else return `${__dirname}/`;
}
Jimp.dirName = getJimpDir();
// Font locations
Jimp.FONT_SANS_8_BLACK = Jimp.dirName + "fonts/open-sans/open-sans-8-black/open-sans-8-black.fnt";
Jimp.FONT_SANS_10_BLACK = Jimp.dirName + "fonts/open-sans/open-sans-10-black/open-sans-10-black.fnt";
Jimp.FONT_SANS_12_BLACK = Jimp.dirName + "fonts/open-sans/open-sans-12-black/open-sans-12-black.fnt";
Jimp.FONT_SANS_14_BLACK = Jimp.dirName + "fonts/open-sans/open-sans-14-black/open-sans-14-black.fnt";
Jimp.FONT_SANS_16_BLACK = Jimp.dirName + "fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt";
Jimp.FONT_SANS_32_BLACK = Jimp.dirName + "fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt";
Jimp.FONT_SANS_64_BLACK = Jimp.dirName + "fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt";
Jimp.FONT_SANS_128_BLACK = Jimp.dirName + "fonts/open-sans/open-sans-128-black/open-sans-128-black.fnt";
Jimp.FONT_SANS_8_WHITE = Jimp.dirName + "fonts/open-sans/open-sans-8-white/open-sans-8-white.fnt";
Jimp.FONT_SANS_16_WHITE = Jimp.dirName + "fonts/open-sans/open-sans-16-white/open-sans-16-white.fnt";
Jimp.FONT_SANS_32_WHITE = Jimp.dirName + "fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt";
Jimp.FONT_SANS_64_WHITE = Jimp.dirName + "fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt";
Jimp.FONT_SANS_128_WHITE = Jimp.dirName + "fonts/open-sans/open-sans-128-white/open-sans-128-white.fnt";
// Edge Handling
Jimp.EDGE_EXTEND = 1;
Jimp.EDGE_WRAP = 2;
Jimp.EDGE_CROP = 3;
/**
* A static helper method that converts RGBA values to a single integer value
* @param r the red value (0-255)
* @param g the green value (0-255)
* @param b the blue value (0-255)
* @param a the alpha value (0-255)
* @param cb (optional) A callback for when complete
* @returns an single integer colour value
*/
Jimp.rgbaToInt = function (r, g, b, a, cb) {
if (typeof r !== "number" || typeof g !== "number" || typeof b !== "number" || typeof a !== "number")
return throwError.call(this, "r, g, b and a must be numbers", cb);
if (r < 0 || r > 255)
return throwError.call(this, "r must be between 0 and 255", cb);
if (g < 0 || g > 255)
throwError.call(this, "g must be between 0 and 255", cb);
if (b < 0 || b > 255)
return throwError.call(this, "b must be between 0 and 255", cb);
if (a < 0 || a > 255)
return throwError.call(this, "a must be between 0 and 255", cb);
r = Math.round(r);
b = Math.round(b);
g = Math.round(g);
a = Math.round(a);
var i = (r * Math.pow(256, 3)) + (g * Math.pow(256, 2)) + (b * Math.pow(256, 1)) + (a * Math.pow(256, 0));
if (isNodePattern(cb)) return cb.call(this, null, i);
else return i;
}
/**
* A static helper method that converts RGBA values to a single integer value
* @param i a single integer value representing an RGBA colour (e.g. 0xFF0000FF for red)
* @param cb (optional) A callback for when complete
* @returns an object with the properties r, g, b and a representing RGBA values
*/
Jimp.intToRGBA = function (i, cb) {
if (typeof i !== "number")
return throwError.call(this, "i must be a number", cb);
var rgba = {}
rgba.r = Math.floor(i / Math.pow(256, 3));
rgba.g = Math.floor((i - (rgba.r * Math.pow(256, 3))) / Math.pow(256, 2));
rgba.b = Math.floor((i - (rgba.r * Math.pow(256, 3)) - (rgba.g * Math.pow(256, 2))) / Math.pow(256, 1));
rgba.a = Math.floor((i - (rgba.r * Math.pow(256, 3)) - (rgba.g * Math.pow(256, 2)) - (rgba.b * Math.pow(256, 1))) / Math.pow(256, 0));
if (isNodePattern(cb)) return cb.call(this, null, rgba);
else return rgba;
}
/**
* Limits a number to between 0 or 255
* @param n a number
* @returns the number limited to between 0 or 255
*/
Jimp.limit255 = function (n) {
n = Math.max(n, 0);
n = Math.min(n, 255);
return n;
}
/**
* Diffs two images and returns
* @param img1 a Jimp image to compare
* @param img2 a Jimp image to compare
* @param (optional) threshold a number, 0 to 1, the smaller the value the more sensitive the comparison (default: 0.1)
* @returns an object { percent: percent similar, diff: a Jimp image highlighting differences }
*/
Jimp.diff = function (img1, img2, threshold) {
if (!(img1 instanceof Jimp) || !(img2 instanceof Jimp))
return throwError.call(this, "img1 and img2 must be an Jimp images");
var bmp1 = img1.bitmap;
var bmp2 = img2.bitmap;
if (bmp1.width !== bmp2.width || bmp1.height !== bmp2.height) {
if (bmp1.width * bmp1.height > bmp2.width * bmp2.height) {
// img1 is bigger
img1 = img1.cloneQuiet().resize(bmp2.width, bmp2.height);
} else {
// img2 is bigger (or they are the same in area)
img2 = img2.cloneQuiet().resize(bmp1.width, bmp1.height);
}
}
threshold = isDef(threshold) ? threshold : 0.1;
if (typeof threshold !== "number" || threshold < 0 || threshold > 1)
return throwError.call(this, "threshold must be a number between 0 and 1");
var diff = new Jimp(bmp1.width, bmp1.height, 0xFFFFFFFF);
var numDiffPixels = PixelMatch(
bmp1.data,
bmp2.data,
diff.bitmap.data,
diff.bitmap.width,
diff.bitmap.height,
{threshold: threshold}
);
return {
percent: numDiffPixels / (diff.bitmap.width * diff.bitmap.height),
image: diff
};
}
/**
* Calculates the hamming distance of two images based on their perceptual hash
* @param img1 a Jimp image to compare
* @param img2 a Jimp image to compare
* @returns a number ranging from 0 to 1, 0 means they are believed to be identical
*/
Jimp.distance = function (img1, img2) {
var phash = new ImagePHash();
var hash1 = phash.getHash(img1);
var hash2 = phash.getHash(img2);
return phash.distance(hash1, hash2);
}
// An object representing a bitmap in memory, comprising:
// - data: a buffer of the bitmap data
// - width: the width of the image in pixels
// - height: the height of the image in pixels
Jimp.prototype.bitmap = {
data: null,
width: null,
height: null
};
// The quality to be used when saving JPEG images
Jimp.prototype._quality = 100;
Jimp.prototype._deflateLevel = 9;
Jimp.prototype._deflateStrategy = 3;
Jimp.prototype._filterType = Jimp.PNG_FILTER_AUTO;
// Whether PNGs will be exported as RGB or RGBA
Jimp.prototype._rgba = true;
// Default colour to use for new pixels
Jimp.prototype._background = 0x00000000;
// Default MIME is PNG
Jimp.prototype._originalMime = Jimp.MIME_PNG;
// Exif data for the image
Jimp.prototype._exif = null;
/**
* Creates a new image that is a clone of this one.
* @param cb (optional) A callback for when complete
* @returns the new image
*/
JimpEvMethod("clone", "clone", function (cb) {
var clone = new Jimp(this);
if (isNodePattern(cb)) return cb.call(clone, null, clone);
else return clone;
});
/**
* Sets the quality of the image when saving as JPEG format (default is 100)
* @param n The quality to use 0-100
* @param (optional) cb a callback for when complete
* @returns this for chaining of methods
*/
Jimp.prototype.quality = function (n, cb) {
if (typeof n !== "number")
return throwError.call(this, "n must be a number", cb);
if (n < 0 || n > 100)
return throwError.call(this, "n must be a number 0 - 100", cb);
this._quality = Math.round(n);
if (isNodePattern(cb)) return cb.call(this, null, this);
else return this;
};
/**
* Sets the deflate level used when saving as PNG format (default is 9)
* @param l Deflate level to use 0-9. 0 is no compression. 9 (default) is maximum compression.
* @param (optional) cb a callback for when complete
* @returns this for chaining of methods
*/
Jimp.prototype.deflateLevel = function (l, cb) {
if (typeof l !== "number")
return throwError.call(this, "l must be a number", cb);
if (l < 0 || l > 9)
return throwError.call(this, "l must be a number 0 - 9", cb);
this._deflateLevel = Math.round(l);
if (isNodePattern(cb)) return cb.call(this, null, this);
else return this;
};
/**
* Sets the deflate strategy used when saving as PNG format (default is 3)
* @param s Deflate strategy to use 0-3.
* @param (optional) cb a callback for when complete
* @returns this for chaining of methods
*/
Jimp.prototype.deflateStrategy = function (s, cb) {
if (typeof s !== "number")
return throwError.call(this, "s must be a number", cb);
if (s < 0 || s > 3)
return throwError.call(this, "s must be a number 0 - 3", cb);
this._deflateStrategy = Math.round(s);
if (isNodePattern(cb)) return cb.call(this, null, this);
else return this;
};
/**
* Sets the filter type used when saving as PNG format (default is automatic filters)
* @param f The quality to use -1-4.
* @param (optional) cb a callback for when complete
* @returns this for chaining of methods
*/
Jimp.prototype.filterType = function (f, cb) {
if (typeof f !== "number")
return throwError.call(this, "n must be a number", cb);
if (f < -1 || f > 4)
return throwError.call(this, "n must be -1 (auto) or a number 0 - 4", cb);
this._filterType = Math.round(f);
if (isNodePattern(cb)) return cb.call(this, null, this);
else return this;
};
/**
* Sets the type of the image (RGB or RGBA) when saving as PNG format (default is RGBA)
* @param bool A Boolean, true to use RGBA or false to use RGB
* @param (optional) cb a callback for when complete
* @returns this for chaining of methods
*/
Jimp.prototype.rgba = function (bool, cb) {
if (typeof bool !== "boolean")
return throwError.call(this, "bool must be a boolean, true for RGBA or false for RGB", cb);
this._rgba = bool;
if (isNodePattern(cb)) return cb.call(this, null, this);
else return this;
};
/**
* Sets the type of the image (RGB or RGBA) when saving as PNG format (default is RGBA)
* @param b A Boolean, true to use RGBA or false to use RGB
* @param (optional) cb a callback for when complete
* @returns this for chaining of methods
*/
JimpEvChange("background", function background (hex, cb) {
if (typeof hex !== "number")
return throwError.call(this, "hex must be a hexadecimal rgba value", cb);
this._background = hex;
if (isNodePattern(cb)) return cb.call(this, null, this);
else return this;
});
/**
* Scanes through a region of the bitmap, calling a function for each pixel.
* @param x the x coordinate to begin the scan at
* @param y the y coordiante to begin the scan at
* @param w the width of the scan region
* @param h the height of the scan region
* @param f a function to call on even pixel; the (x, y) position of the pixel
* and the index of the pixel in the bitmap buffer are passed to the function
* @param (optional) cb a callback for when complete
* @returns this for chaining of methods
*/
JimpEvChange("scan", function scan (x, y, w, h, f, cb) {
if (typeof x !== "number" || typeof y !== "number")
return throwError.call(this, "x and y must be numbers", cb);
if (typeof w !== "number" || typeof h !== "number")
return throwError.call(this, "w and h must be numbers", cb);
if (typeof f !== "function")
return throwError.call(this, "f must be a function", cb);
// round input
x = Math.round(x);
y = Math.round(y);
w = Math.round(w);
h = Math.round(h);
for (let _y = y; _y < (y + h); _y++) {
for (let _x = x; _x < (x + w); _x++) {
var idx = (this.bitmap.width * _y + _x) << 2;
f.call(this, _x, _y, idx);
}
}
if (isNodePattern(cb)) return cb.call(this, null, this);
else return this;
});
/**
* Returns the original MIME of the image (default: "image/png")
* @returns the MIME as a string
*/
Jimp.prototype.getMIME = function () {
var mime = this._originalMime || Jimp.MIME_PNG;
return mime;
}
/**
* Returns the appropriate file extension for the original MIME of the image (default: "png")
* @returns the file extension as a string
*/
Jimp.prototype.getExtension = function () {
var mime = this.getMIME();
return MIME.extension(mime);
}
/**
* Returns the offset of a pixel in the bitmap buffer
* @param x the x coordinate
* @param y the y coordinate
* @param (optional) edgeHandling define how to sum pixels from outside the border
* @param (optional) cb a callback for when complete
* @returns the index of the pixel or -1 if not found
*/
Jimp.prototype.getPixelIndex = function (x, y, edgeHandling, cb) {
var xi, yi;
if (typeof edgeHandling === "function" && typeof cb === "undefined") {
cb = edgeHandling;
edgeHandling = null;
}
if (!edgeHandling) edgeHandling = Jimp.EDGE_EXTEND;
if (typeof x !== "number" || typeof y !== "number")
return throwError.call(this, "x and y must be numbers", cb);
// round input
xi = x = Math.round(x);
yi = y = Math.round(y);
if (edgeHandling === Jimp.EDGE_EXTEND) {
if (x<0) xi = 0;
if (x>=this.bitmap.width) xi = this.bitmap.width - 1;
if (y<0) yi = 0;
if (y>=this.bitmap.height) yi = this.bitmap.height - 1;
}
if (edgeHandling === Jimp.EDGE_WRAP) {
if (x<0) xi = this.bitmap.width + x;
if (x>=this.bitmap.width) xi = x % this.bitmap.width;
if (y<0) xi = this.bitmap.height + y;
if (y>=this.bitmap.height) yi = y % this.bitmap.height;
}
var i = (this.bitmap.width * yi + xi) << 2;
// if out of bounds index is -1
if (xi < 0 || xi >= this.bitmap.width) i = -1;
if (yi < 0 || yi >= this.bitmap.height) i = -1;
if (isNodePattern(cb)) return cb.call(this, null, i);
else return i;
};
/**
* Returns the hex colour value of a pixel
* @param x the x coordinate
* @param y the y coordinate
* @param (optional) cb a callback for when complete
* @returns the color of the pixel
*/
Jimp.prototype.getPixelColor = Jimp.prototype.getPixelColour = function (x, y, cb) {
if (typeof x !== "number" || typeof y !== "number")
return throwError.call(this, "x and y must be numbers", cb);
// round input
x = Math.round(x);
y = Math.round(y);
var idx = this.getPixelIndex(x, y);
var hex = this.bitmap.data.readUInt32BE(idx);
if (isNodePattern(cb)) return cb.call(this, null, hex);
else return hex;
};
/**
* Returns the hex colour value of a pixel
* @param x the x coordinate
* @param y the y coordinate
* @param (optional) cb a callback for when complete
* @returns the index of the pixel or -1 if not found
*/
Jimp.prototype.setPixelColor = Jimp.prototype.setPixelColour = function (hex, x, y, cb) {
if (typeof hex !== "number" || typeof x !== "number" || typeof y !== "number")
return throwError.call(this, "hex, x and y must be numbers", cb);
// round input
x = Math.round(x);
y = Math.round(y);
var idx = this.getPixelIndex(x, y);
this.bitmap.data.writeUInt32BE(hex, idx);
if (isNodePattern(cb)) return cb.call(this, null, this);
else return this;
};
// an array storing the maximum string length of hashes at various bases
var maxHashLength = [];
for (let i = 0; i < 65; i++) {
var l = (i > 1) ? (new BigNumber(Array(64 + 1).join("1"), 2)).toString(i) : NaN;
maxHashLength.push(l.length);
}
/**
* Generates a perceptual hash of the image <https://en.wikipedia.org/wiki/Perceptual_hashing>.
* @param base (optional) a number between 2 and 64 representing the base for the hash (e.g. 2 is binary, 10 is decimaal, 16 is hex, 64 is base 64). Defaults to 64.
* @param (optional) cb a callback for when complete
* @returns a string representing the hash
*/
Jimp.prototype.hash = function (base, cb) {
base = base || 64;
if (typeof base === "function") {
cb = base;
base = 64;
}
if (typeof base !== "number")
return throwError.call(this, "base must be a number", cb);
if (base < 2 || base > 64)
return throwError.call(this, "base must be a number between 2 and 64", cb);
var hash = (new ImagePHash()).getHash(this);
hash = (new BigNumber(hash, 2)).toString(base);
while (hash.length < maxHashLength[base]) {
hash = "0" + hash; // pad out with leading zeros
}
if (isNodePattern(cb)) return cb.call(this, null, hash);
else return hash;
}
/**
* Crops the image at a given point to a give size
* @param x the x coordinate to crop form
* @param y the y coordiante to crop form
* @param w the width of the crop region
* @param h the height of the crop region
* @param (optional) cb a callback for when complete
* @returns this for chaining of methods
*/
JimpEvChange("crop", function crop (x, y, w, h, cb) {
if (typeof x !== "number" || typeof y !== "number")
return throwError.call(this, "x and y must be numbers", cb);
if (typeof w !== "number" || typeof h !== "number")
return throwError.call(this, "w and h must be numbers", cb);
// round input
x = Math.round(x);
y = Math.round(y);
w = Math.round(w);
h = Math.round(h);
var bitmap = new Buffer(this.bitmap.data.length);
var offset = 0;
this.scanQuiet(x, y, w, h, function (x, y, idx) {
var data = this.bitmap.data.readUInt32BE(idx);
bitmap.writeUInt32BE(data, offset);
offset += 4;
});