-
-
Notifications
You must be signed in to change notification settings - Fork 777
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·1238 lines (1015 loc) · 32.5 KB
/
Copy pathindex.js
File metadata and controls
executable file
·1238 lines (1015 loc) · 32.5 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
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
import fs from "fs";
import Path from "path";
import EventEmitter from "events";
import { isNodePattern, throwError, scan, scanIterator } from "@jimp/utils";
import anyBase from "any-base";
import pixelMatch from "pixelmatch";
import tinyColor from "tinycolor2";
import ImagePHash from "./modules/phash";
import request from "./request";
import composite from "./composite";
import promisify from "./utils/promisify";
import * as MIME from "./utils/mime";
import { parseBitmap, getBuffer, getBufferAsync } from "./utils/image-bitmap";
import * as constants from "./constants";
const alphabet =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_";
// an array storing the maximum string length of hashes at various bases
// 0 and 1 do not exist as possible hash lengths
const maxHashLength = [NaN, NaN];
for (let i = 2; i < 65; i++) {
const maxHash = anyBase(
anyBase.BIN,
alphabet.slice(0, i)
)(new Array(64 + 1).join("1"));
maxHashLength.push(maxHash.length);
}
// no operation
function noop() {}
// error checking methods
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) {
const buffer = Buffer.alloc(arrayBuffer.byteLength);
const view = new Uint8Array(arrayBuffer);
for (let i = 0; i < buffer.length; ++i) {
buffer[i] = view[i];
}
return buffer;
}
function loadFromURL(options, cb) {
request(options, (err, data) => {
if (err) {
return cb(err);
}
if (typeof data === "object" && Buffer.isBuffer(data)) {
return cb(null, data);
}
if (typeof data === "object" && isArrayBuffer(data)) {
return cb(null, bufferFromArrayBuffer(data));
}
return new Error(`Could not load Buffer from <${options.url}>`);
});
}
function loadBufferFromPath(src, cb) {
if (
fs &&
typeof fs.readFile === "function" &&
!src.match(/^(http|ftp)s?:\/\/./)
) {
fs.readFile(src, cb);
} else {
loadFromURL({ url: src }, cb);
}
}
function isRawRGBAData(obj) {
return (
obj &&
typeof obj === "object" &&
typeof obj.width === "number" &&
typeof obj.height === "number" &&
(Buffer.isBuffer(obj.data) ||
obj.data instanceof Uint8Array ||
(typeof Uint8ClampedArray === "function" &&
obj.data instanceof Uint8ClampedArray)) &&
(obj.data.length === obj.width * obj.height * 4 ||
obj.data.length === obj.width * obj.height * 3)
);
}
function makeRGBABufferFromRGB(buffer) {
if (buffer.length % 3 !== 0) {
throw new Error("Buffer length is incorrect");
}
const rgbaBuffer = Buffer.allocUnsafe((buffer.length / 3) * 4);
let j = 0;
for (let i = 0; i < buffer.length; i++) {
rgbaBuffer[j] = buffer[i];
if ((i + 1) % 3 === 0) {
rgbaBuffer[++j] = 255;
}
j++;
}
return rgbaBuffer;
}
const emptyBitmap = {
data: null,
width: null,
height: null,
};
/**
* Jimp constructor (from a file)
* @param path a path to the image
* @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap
*/
/**
* Jimp constructor (from a url with options)
* @param options { url, otherOptions}
* @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap
*/
/**
* Jimp constructor (from another Jimp image or raw image data)
* @param image a Jimp image to clone
* @param {function(Error, Jimp)} 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 {function(Error, Jimp)} 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 {function(Error, Jimp)} cb (optional) 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 background color to fill the image with
* @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap
*/
class Jimp extends EventEmitter {
// 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
bitmap = emptyBitmap;
// Default colour to use for new pixels
_background = 0x00000000;
// Default MIME is PNG
_originalMime = Jimp.MIME_PNG;
// Exif data for the image
_exif = null;
// Whether Transparency supporting formats will be exported as RGB or RGBA
_rgba = true;
constructor(...args) {
super();
const jimpInstance = this;
let cb = noop;
if (isArrayBuffer(args[0])) {
args[0] = bufferFromArrayBuffer(args[0]);
}
function finish(...args) {
const [err] = args;
const evData = err || {};
evData.methodName = "constructor";
setTimeout(() => {
// run on next tick.
if (err && cb === noop) {
jimpInstance.emitError("constructor", err);
} else if (!err) {
jimpInstance.emitMulti("constructor", "initialized");
}
cb.call(jimpInstance, ...args);
}, 1);
}
if (
(typeof args[0] === "number" && typeof args[1] === "number") ||
(parseInt(args[0], 10) && parseInt(args[1], 10))
) {
// create a new image
const w = parseInt(args[0], 10);
const h = parseInt(args[1], 10);
cb = args[2];
// with a hex color
if (typeof args[2] === "number") {
this._background = args[2];
cb = args[3];
}
// with a css color
if (typeof args[2] === "string") {
this._background = Jimp.cssColorToHex(args[2]);
cb = args[3];
}
if (typeof cb === "undefined") {
cb = noop;
}
if (typeof cb !== "function") {
return throwError.call(this, "cb must be a function", finish);
}
this.bitmap = {
data: Buffer.alloc(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 (typeof args[0] === "object" && args[0].url) {
cb = args[1] || noop;
if (typeof cb !== "function") {
return throwError.call(this, "cb must be a function", finish);
}
loadFromURL(args[0], (err, data) => {
if (err) {
return throwError.call(this, err, finish);
}
this.parseBitmap(data, args[0].url, finish);
});
} else if (args[0] instanceof Jimp) {
// clone an existing Jimp
const [original] = args;
cb = args[1];
if (typeof cb === "undefined") {
cb = noop;
}
if (typeof cb !== "function") {
return throwError.call(this, "cb must be a function", finish);
}
this.bitmap = {
data: Buffer.from(original.bitmap.data),
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;
this._originalMime = original._originalMime;
finish(null, this);
} else if (isRawRGBAData(args[0])) {
const [imageData] = args;
cb = args[1] || noop;
const isRGBA =
imageData.width * imageData.height * 4 === imageData.data.length;
const buffer = isRGBA
? Buffer.from(imageData.data)
: makeRGBABufferFromRGB(imageData.data);
this.bitmap = {
data: buffer,
width: imageData.width,
height: imageData.height,
};
finish(null, this);
} else if (typeof args[0] === "string") {
// read from a path
const path = args[0];
cb = args[1];
if (typeof cb === "undefined") {
cb = noop;
}
if (typeof cb !== "function") {
return throwError.call(this, "cb must be a function", finish);
}
loadBufferFromPath(path, (err, data) => {
if (err) {
return throwError.call(this, err, finish);
}
this.parseBitmap(data, path, finish);
});
} else if (typeof args[0] === "object" && Buffer.isBuffer(args[0])) {
// read from a buffer
const data = args[0];
cb = args[1];
if (typeof cb !== "function") {
return throwError.call(this, "cb must be a function", finish);
}
this.parseBitmap(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 = args[args.length - 1];
if (typeof cb !== "function") {
// TODO: try to solve the args after cb problem.
cb = args[args.length - 2];
if (typeof cb !== "function") {
cb = noop;
}
}
const extraConstructor = Jimp.__extraConstructors.find((c) =>
c.test(...args)
);
if (extraConstructor) {
new Promise((resolve, reject) => {
extraConstructor.run.call(this, resolve, reject, ...args);
})
.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
);
}
}
}
/**
* Parse a bitmap with the loaded image types.
*
* @param {Buffer} data raw image data
* @param {string} path optional path to file
* @param {function(Error, Jimp)} finish (optional) a callback for when complete
* @memberof Jimp
*/
parseBitmap(data, path, finish) {
parseBitmap.call(this, data, null, finish);
}
/**
* Sets the type of the image (RGB or RGBA) when saving in a format that supports transparency (default is RGBA)
* @param {boolean} bool A Boolean, true to use RGBA or false to use RGB
* @param {function(Error, Jimp)} cb (optional) a callback for when complete
* @returns {Jimp} this for chaining of methods
*/
rgba(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)) {
cb.call(this, null, this);
}
return this;
}
/**
* Emit for multiple listeners
* @param {string} methodName name of the method to emit an error for
* @param {string} eventName name of the eventName to emit an error for
* @param {object} data to emit
*/
emitMulti(methodName, eventName, data = {}) {
data = Object.assign(data, { methodName, eventName });
this.emit("any", data);
if (methodName) {
this.emit(methodName, data);
}
this.emit(eventName, data);
}
emitError(methodName, err) {
this.emitMulti(methodName, "error", err);
}
/**
* Get the current height of the image
* @return {number} height of the image
*/
getHeight() {
return this.bitmap.height;
}
/**
* Get the current width of the image
* @return {number} width of the image
*/
getWidth() {
return this.bitmap.width;
}
/**
* Nicely format Jimp object when sent to the console e.g. console.log(image)
* @returns {string} pretty printed
*/
inspect() {
return (
"<Jimp " +
(this.bitmap === emptyBitmap
? "pending..."
: this.bitmap.width + "x" + this.bitmap.height) +
">"
);
}
/**
* Nicely format Jimp object when converted to a string
* @returns {string} pretty printed
*/
toString() {
return "[object Jimp]";
}
/**
* Returns the original MIME of the image (default: "image/png")
* @returns {string} the MIME
*/
getMIME() {
const mime = this._originalMime || Jimp.MIME_PNG;
return mime;
}
/**
* Returns the appropriate file extension for the original MIME of the image (default: "png")
* @returns {string} the file extension
*/
getExtension() {
const mime = this.getMIME();
return MIME.getExtension(mime);
}
/**
* Writes the image to a file
* @param {string} path a path to the destination file
* @param {function(Error, Jimp)} cb (optional) a function to call when the image is saved to disk
* @returns {Jimp} this for chaining of methods
*/
write(path, cb) {
if (!fs || !fs.createWriteStream) {
throw new Error(
"Cant access the filesystem. You can use the getBase64 method."
);
}
if (typeof path !== "string") {
return throwError.call(this, "path must be a string", cb);
}
if (typeof cb === "undefined") {
cb = noop;
}
if (typeof cb !== "function") {
return throwError.call(this, "cb must be a function", cb);
}
const mime = MIME.getType(path) || this.getMIME();
const pathObj = Path.parse(path);
if (pathObj.dir) {
fs.mkdirSync(pathObj.dir, { recursive: true });
}
this.getBuffer(mime, (err, buffer) => {
if (err) {
return throwError.call(this, err, cb);
}
const stream = fs.createWriteStream(path);
stream
.on("open", () => {
stream.write(buffer);
stream.end();
})
.on("error", (err) => {
return throwError.call(this, err, cb);
});
stream.on("finish", () => {
cb.call(this, null, this);
});
});
return this;
}
writeAsync = (path) => promisify(this.write, this, path);
/**
* Converts the image to a base 64 string
* @param {string} mime the mime type of the image data to be created
* @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument
* @returns {Jimp} this for chaining of methods
*/
getBase64(mime, cb) {
if (mime === Jimp.AUTO) {
// allow auto MIME detection
mime = this.getMIME();
}
if (typeof mime !== "string") {
return throwError.call(this, "mime must be a string", cb);
}
if (typeof cb !== "function") {
return throwError.call(this, "cb must be a function", cb);
}
this.getBuffer(mime, function (err, data) {
if (err) {
return throwError.call(this, err, cb);
}
const src = "data:" + mime + ";base64," + data.toString("base64");
cb.call(this, null, src);
});
return this;
}
getBase64Async = (mime) => promisify(this.getBase64, this, mime);
/**
* Generates a perceptual hash of the image <https://en.wikipedia.org/wiki/Perceptual_hashing>. And pads the string. Can configure base.
* @param {number} base (optional) a number between 2 and 64 representing the base for the hash (e.g. 2 is binary, 10 is decimal, 16 is hex, 64 is base 64). Defaults to 64.
* @param {function(Error, Jimp)} cb (optional) a callback for when complete
* @returns {string} a string representing the hash
*/
hash(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
);
}
let hash = this.pHash();
hash = anyBase(anyBase.BIN, alphabet.slice(0, base))(hash);
while (hash.length < maxHashLength[base]) {
hash = "0" + hash; // pad out with leading zeros
}
if (isNodePattern(cb)) {
cb.call(this, null, hash);
}
return hash;
}
/**
* Calculates the perceptual hash
* @returns {number} the perceptual hash
*/
pHash() {
const pHash = new ImagePHash();
return pHash.getHash(this);
}
/**
* Calculates the hamming distance of the current image and a hash based on their perceptual hash
* @param {hash} compareHash hash to compare to
* @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical
*/
distanceFromHash(compareHash) {
const pHash = new ImagePHash();
const currentHash = pHash.getHash(this);
return pHash.distance(currentHash, compareHash);
}
/**
* Converts the image to a buffer
* @param {string} mime the mime type of the image buffer to be created
* @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument
* @returns {Jimp} this for chaining of methods
*/
getBuffer = getBuffer;
getBufferAsync = getBufferAsync;
/**
* Returns the offset of a pixel in the bitmap buffer
* @param {number} x the x coordinate
* @param {number} y the y coordinate
* @param {number} edgeHandling (optional) define how to sum pixels from outside the border
* @param {number} cb (optional) a callback for when complete
* @returns {number} the index of the pixel or -1 if not found
*/
getPixelIndex(x, y, edgeHandling, cb) {
let xi;
let 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
x = Math.round(x);
y = Math.round(y);
xi = x;
yi = 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) {
yi = this.bitmap.height + y;
}
if (y >= this.bitmap.height) {
yi = y % this.bitmap.height;
}
}
let 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)) {
cb.call(this, null, i);
}
return i;
}
/**
* Returns the hex colour value of a pixel
* @param {number} x the x coordinate
* @param {number} y the y coordinate
* @param {function(Error, Jimp)} cb (optional) a callback for when complete
* @returns {number} the color of the pixel
*/
getPixelColor(x, y, cb) {
if (typeof x !== "number" || typeof y !== "number")
return throwError.call(this, "x and y must be numbers", cb);
const idx = this.getPixelIndex(x, y);
const hex = this.bitmap.data.readUInt32LE(idx);
if (isNodePattern(cb)) {
cb.call(this, null, hex);
}
return hex;
}
getPixelColour = this.getPixelColor;
/**
* Returns the hex colour value of a pixel
* @param {number} hex color to set
* @param {number} x the x coordinate
* @param {number} y the y coordinate
* @param {function(Error, Jimp)} cb (optional) a callback for when complete
* @returns {number} the index of the pixel or -1 if not found
*/
setPixelColor(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);
const idx = this.getPixelIndex(x, y);
this.bitmap.data.writeUInt32BE(hex, idx);
if (isNodePattern(cb)) {
cb.call(this, null, this);
}
return this;
}
setPixelColour = this.setPixelColor;
/**
* Determine if the image contains opaque pixels.
* @return {boolean} hasAlpha whether the image contains opaque pixels
*/
hasAlpha() {
const {width, height, data} = this.bitmap;
const byteLen = (width * height) << 2;
for (let idx = 3; idx < byteLen; idx += 4) {
if (data[idx] !== 0xff) {
return true;
}
}
return false;
}
/**
* Iterate scan through a region of the bitmap
* @param {number} x the x coordinate to begin the scan at
* @param {number} y the y coordinate to begin the scan at
* @param w the width of the scan region
* @param h the height of the scan region
* @returns {IterableIterator<{x: number, y: number, idx: number, image: Jimp}>}
*/
scanIterator(x, y, w, h) {
if (typeof x !== "number" || typeof y !== "number") {
return throwError.call(this, "x and y must be numbers");
}
if (typeof w !== "number" || typeof h !== "number") {
return throwError.call(this, "w and h must be numbers");
}
return scanIterator(this, x, y, w, h);
}
}
export function addConstants(constants, jimpInstance = Jimp) {
Object.entries(constants).forEach(([name, value]) => {
jimpInstance[name] = value;
});
}
export function addJimpMethods(methods, jimpInstance = Jimp) {
Object.entries(methods).forEach(([name, value]) => {
jimpInstance.prototype[name] = value;
});
}
addConstants(constants);
addJimpMethods({ composite });
Jimp.__extraConstructors = [];
/**
* Allow client libs to add new ways to build a Jimp object.
* @param {string} name identify the extra constructor.
* @param {function} test a function that returns true when it accepts the arguments passed to the main constructor.
* @param {function} run where the magic happens.
*/
Jimp.appendConstructorOption = function (name, test, run) {
Jimp.__extraConstructors.push({ name, test, run });
};
/**
* Read an image from a file or a Buffer. Takes the same args as the constructor
* @returns {Promise} a promise
*/
Jimp.read = function (...args) {
return new Promise((resolve, reject) => {
// eslint-disable-next-line no-new
new Jimp(...args, (err, image) => {
if (err) reject(err);
else resolve(image);
});
});
};
Jimp.create = Jimp.read;
/**
* A static helper method that converts RGBA values to a single integer value
* @param {number} r the red value (0-255)
* @param {number} g the green value (0-255)
* @param {number} b the blue value (0-255)
* @param {number} a the alpha value (0-255)
* @param {function(Error, Jimp)} cb (optional) A callback for when complete
* @returns {number} 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);
}
let i = (r & 0xff);
i <<= 8;
i |= (g & 0xff)
i <<= 8;
i |= (b & 0xff)
i <<= 8;
i |= (a & 0xff);
// Ensure sign is correct
i >>>= 0;
if (isNodePattern(cb)) {
cb.call(this, null, i);
}
return i;
};
/**
* A static helper method that converts RGBA values to a single integer value
* @param {number} i a single integer value representing an RGBA colour (e.g. 0xFF0000FF for red)
* @param {function(Error, Jimp)} cb (optional) A callback for when complete
* @returns {object} 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);
}
const 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)) {
cb.call(this, null, rgba);
}
return rgba;
};
/**
* Converts a css color (Hex, 8-digit (RGBA) Hex, RGB, RGBA, HSL, HSLA, HSV, HSVA, Named) to a hex number
* @param {string} cssColor a number
* @returns {number} a hex number representing a color
*/
Jimp.cssColorToHex = function (cssColor) {
cssColor = cssColor || 0; // 0, null, undefined, NaN
if (typeof cssColor === "number") return Number(cssColor);
return parseInt(tinyColor(cssColor).toHex8(), 16);
};
/**
* Limits a number to between 0 or 255
* @param {number} n a number
* @returns {number} 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 {Jimp} img1 a Jimp image to compare
* @param {Jimp} img2 a Jimp image to compare
* @param {number} threshold (optional) a number, 0 to 1, the smaller the value the more sensitive the comparison (default: 0.1)
* @returns {object} an object { percent: percent similar, diff: a Jimp image highlighting differences }
*/
Jimp.diff = function (img1, img2, threshold = 0.1) {
if (!(img1 instanceof Jimp) || !(img2 instanceof Jimp))
return throwError.call(this, "img1 and img2 must be an Jimp images");
const bmp1 = img1.bitmap;
const 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);
}
}
if (typeof threshold !== "number" || threshold < 0 || threshold > 1) {
return throwError.call(this, "threshold must be a number between 0 and 1");