-
Notifications
You must be signed in to change notification settings - Fork 32
/
ImageScript.js
1669 lines (1429 loc) · 54.4 KB
/
ImageScript.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
const png = require('./png/node.js');
const mem = require('./utils/mem.js');
const {version} = require('./package.json');
const codecs = require('./codecs/node/index.js');
const { default: v2 } = require('./v2/framebuffer.js');
// old
const svglib = require('./wasm/node/svg.js');
const giflib = require('./wasm/node/gif.js');
const pnglib = require('./wasm/node/png.js');
const fontlib = require('./wasm/node/font.js');
const jpeglib = require('./wasm/node/jpeg.js');
const tifflib = require('./wasm/node/tiff.js');
const MAGIC_NUMBERS = {
PNG: 0x89504e47,
JPEG: 0xffd8ff,
TIFF: 0x49492a00,
GIF: 0x474946
};
/**
* Represents an image; provides utility functions
*/
class Image {
/**
* Creates a new image with the given dimensions
* @param {number} width
* @param {number} height
* @returns {Image}
*/
constructor(width, height) {
width = ~~width;
height = ~~height;
if (width < 1)
throw new RangeError('Image has to be at least 1 pixel wide');
if (height < 1)
throw new RangeError('Image has to be at least 1 pixel high');
/** @private */
this.__width__ = width;
/** @private */
this.__height__ = height;
/** @private */
this.__buffer__ = new ArrayBuffer(width * height * 4);
/** @private */
this.__view__ = new DataView(this.__buffer__);
/** @private */
this.__u32__ = new Uint32Array(this.__buffer__);
/**
* The images RGBA pixel data
* @type {Uint8ClampedArray}
*/
this.bitmap = new Uint8ClampedArray(this.__buffer__);
}
/**
* @private
* @returns {string}
*/
toString() {
return `Image<${this.width}x${this.height}>`;
}
/**
* The images width
* @returns {number}
*/
get width() {
return this.__width__;
}
/**
* The images height
* @returns {number}
*/
get height() {
return this.__height__;
}
/**
* Yields an [x, y] array for every pixel in the image
* @yields {number[]} The coordinates of the pixel ([x, y])
* @returns {void}
*/
*[Symbol.iterator]() {
for (const x of new v2(this.width, this.height, this.bitmap)[Symbol.iterator]()) yield (x[0]++, x[1]++, x)
}
/**
* Yields an [x, y, color] array for every pixel in the image
* @yields {number[]} The coordinates and color of the pixel ([x, y, color])
*/
*iterateWithColors() {
for (const x of new v2(this.width, this.height, this.bitmap).pixels('int')) yield (x[0]++, x[1]++, x);
}
/**
* Converts RGBA components to an RGBA value
* @param {number} r red (0..255)
* @param {number} g green (0..255)
* @param {number} b blue (0..255)
* @param {number} a alpha (0..255)
* @returns {number} RGBA value
*/
static rgbaToColor(r, g, b, a) {
return (((r & 0xff) << 24) | ((g & 0xff) << 16) | ((b & 0xff) << 8) | (a & 0xff)) >>> 0;
}
/**
* Converts RGB components to an RGBA value (assuming alpha = 255)
* @param {number} r red (0..255)
* @param {number} g green (0..255)
* @param {number} b blue (0..255)
* @returns {number} RGBA value
*/
static rgbToColor(r, g, b) {
return Image.rgbaToColor(r, g, b, 0xff);
}
/**
* Converts HSLA colors to RGBA colors
* @param {number} h hue (0..1)
* @param {number} s saturation (0..1)
* @param {number} l lightness (0..1)
* @param {number} a opacity (0..1)
* @returns {number} color
*/
static hslaToColor(h, s, l, a) {
h %= 1;
s = Math.min(1, Math.max(0, s));
l = Math.min(1, Math.max(0, l));
a = Math.min(1, Math.max(0, a));
let r, g, b;
if (s === 0) {
r = g = b = l;
} else {
const hue2rgb = (p, q, t) => {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
};
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1 / 3);
}
return Image.rgbaToColor(r * 255, g * 255, b * 255, a * 255);
}
/**
* Converts HSL colors to RGBA colors (assuming an opacity of 255)
* @param {number} h hue (0..1)
* @param {number} s saturation (0..1)
* @param {number} l lightness (0..1)
* @returns {number} color
*/
static hslToColor(h, s, l) {
return Image.hslaToColor(h, s, l, 1);
}
/**
* Converts an RGBA value to an array of HSLA values
* @param r {number} (0..255)
* @param g {number} (0..255)
* @param b {number} (0..255)
* @param a {number} (0..255)
* @returns {number[]} The HSLA values ([H, S, L, A])
*/
static rgbaToHSLA(r, g, b, a) {
r /= 255;
g /= 255;
b /= 255;
const max = Math.max(r, g, b), min = Math.min(r, g, b);
let h, s, l = (max + min) / 2;
if (max === min) {
h = s = 0;
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return [h, s, l, a / 255];
}
/**
* Converts a color value to an array of RGBA values
* @param {number} color The color value to convert
* @returns {number[]} The RGBA values ([R, G, B, A])
*/
static colorToRGBA(color) {
return [(color >> 24) & 0xff, (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff];
}
/**
* Converts a color value to an array of RGB values (ignoring the colors alpha)
* @param {number} color The color value to convert
* @returns {number[]} The RGB values ([R, G, B])
*/
static colorToRGB(color) {
return Image.colorToRGBA(color).slice(0, 3);
}
/**
* Gets the pixel color at the specified position
* @param {number} x
* @param {number} y
* @returns {number} The color value
*/
getPixelAt(x, y) {
this.__check_boundaries__(x, y);
return this.__view__.getUint32(((~~y - 1) * this.width + (~~x - 1)) * 4, false);
}
/**
* Gets the pixel color at the specified position
* @param {number} x
* @param {number} y
* @returns {Uint8ClampedArray} The RGBA value
*/
getRGBAAt(x, y) {
this.__check_boundaries__(x, y);
const idx = ((~~y - 1) * this.width + (~~x - 1)) * 4;
return this.bitmap.subarray(idx, idx + 4);
}
/**
* Sets the pixel color for the specified position
* @param {number} x
* @param {number} y
* @param {number} pixelColor
*/
setPixelAt(x, y, pixelColor) {
x = ~~x;
y = ~~y;
this.__check_boundaries__(x, y);
this.__set_pixel__(x, y, pixelColor);
return this;
}
/**
* @private
* @param {number} x
* @param {number} y
* @param {number} pixelColor
*/
__set_pixel__(x, y, pixelColor) {
this.__view__.setUint32(((y - 1) * this.width + (x - 1)) * 4, pixelColor, false);
}
/**
* @private
* @param {number} x
* @param {number} y
*/
__check_boundaries__(x, y) {
if (isNaN(x)) throw new TypeError(`Invalid pixel coordinates (x=${x})`);
if (isNaN(y)) throw new TypeError(`Invalid pixel coordinates (y=${y})`);
if (x < 1)
throw new RangeError(`${Image.__out_of_bounds__} (x=${x})<1`);
if (x > this.width)
throw new RangeError(`${Image.__out_of_bounds__} (x=${x})>(width=${this.width})`);
if (y < 1)
throw new RangeError(`${Image.__out_of_bounds__} (y=${y})<1`);
if (y > this.height)
throw new RangeError(`${Image.__out_of_bounds__} (y=${y})>(height=${this.height})`);
}
/**
* @private
*/
static get __out_of_bounds__() {
return 'Tried referencing a pixel outside of the images boundaries:';
}
/**
* @callback colorFunction
* @param {number} x
* @param {number} y
* @returns {number} pixel color
*/
/**
* Fills the image data with the supplied color
* @param {number|colorFunction} color
* @returns {Image}
*/
fill(color) {
new v2(this.width, this.height, this.bitmap).fill(color);
return this;
}
/**
* Clones the current image
* @returns {Image}
*/
clone() {
const image = new Image(this.width, this.height);
image.bitmap.set(this.bitmap);
return image;
}
/**
* Use {@link https://en.wikipedia.org/wiki/Image_scaling#Nearest-neighbor_interpolation Nearest-neighbor} resizing.
* @returns {string}
*/
static get RESIZE_NEAREST_NEIGHBOR() {
return 'RESIZE_NEAREST_NEIGHBOR';
}
/**
* Used for automatically preserving an images aspect ratio when resizing.
* @returns {number}
*/
static get RESIZE_AUTO() {
return -1;
}
/**
* Resizes the image by the given factor
* @param {number} factor The factor to resize the image with
* @param {string} [mode=Image.RESIZE_NEAREST_NEIGHBOR] The resizing mode to use
* @returns {Image}
*/
scale(factor, mode = Image.RESIZE_NEAREST_NEIGHBOR) {
const image = this.__scale__(factor, mode);
return this.__apply__(image);
}
/** @private */
__scale__(factor, mode = Image.RESIZE_NEAREST_NEIGHBOR) {
if (factor === 1) return this;
return this.__resize__(this.width * factor, this.height * factor, mode);
}
/**
* Resizes the image to the given dimensions.
* Use {@link Image.RESIZE_AUTO} as either width or height to automatically preserve the aspect ratio.
* @param {number} width The new width
* @param {number} height The new height
* @param {string} [mode=Image.RESIZE_NEAREST_NEIGHBOR] The resizing mode to use
* @returns {Image} The resized image
*/
resize(width, height, mode = Image.RESIZE_NEAREST_NEIGHBOR) {
const image = this.__resize__(width, height, mode);
return this.__apply__(image);
}
/**
* Resizes the image so it is contained in the given bounding box.
* Can return an image with one axis smaller than the given bounding box.
* @param {number} width The width of the bounding box
* @param {number} height The height of the bounding box
* @param {string} [mode=Image.RESIZE_NEAREST_NEIGHBOR] The resizing mode to use
* @returns {Image} The resized image
*/
contain(width, height, mode = Image.RESIZE_NEAREST_NEIGHBOR) {
const scaleFactor = width / height > this.width / this.height ? height / this.height : width / this.width;
return this.scale(scaleFactor, mode);
}
/**
* Resizes the image so it is contained in the given bounding box, placing it in the center of the given bounding box.
* Always returns the exact dimensions of the bounding box.
* @param {number} width The width of the bounding box
* @param {number} height The height of the bounding box
* @param {string} [mode=Image.RESIZE_NEAREST_NEIGHBOR] The resizing mode to use
* @returns {Image} The resized image
*/
fit(width, height, mode = Image.RESIZE_NEAREST_NEIGHBOR) {
const result = new Image(width, height);
this.contain(width, height, mode);
result.composite(this, (width - this.width) / 2, (height - this.height) / 2);
return this.__apply__(result);
}
/**
* Resizes the image so it covers the given bounding box, cropping the overflowing edges.
* Always returns the exact dimensions of the bounding box.
* @param {number} width The width of the bounding box
* @param {number} height The height of the bounding box
* @param {string} [mode=Image.RESIZE_NEAREST_NEIGHBOR] The resizing mode to use
* @returns {Image} The resized image
*/
cover(width, height, mode = Image.RESIZE_NEAREST_NEIGHBOR) {
const scaleFactor = width / height > this.width / this.height ? width / this.width : height / this.height;
const result = this.scale(scaleFactor, mode);
return result.crop((result.width - width) / 2, (result.height - height) / 2, width, height);
}
/** @private */
__resize__(width, height, mode = Image.RESIZE_NEAREST_NEIGHBOR) {
if (width === Image.RESIZE_AUTO && height === Image.RESIZE_AUTO) throw new Error('RESIZE_AUTO can only be used for either width or height, not for both');
else if (width === Image.RESIZE_AUTO) width = this.width / this.height * height;
else if (height === Image.RESIZE_AUTO) height = this.height / this.width * width;
width = Math.floor(width);
height = Math.floor(height);
if (width < 1)
throw new RangeError('Image has to be at least 1 pixel wide');
if (height < 1)
throw new RangeError('Image has to be at least 1 pixel high');
let image;
if (mode === Image.RESIZE_NEAREST_NEIGHBOR)
image = this.__resize_nearest_neighbor__(width, height);
else throw new Error('Invalid resize mode');
return image;
}
/**
* @private
* @param {number} width The new width
* @param {number} height The new height
*/
__resize_nearest_neighbor__(width, height) {
const image = new this.constructor(width, height);
const frame = new v2(this.width, this.height, this.bitmap).resize('nearest', width, height);
image.bitmap.set(frame.u8);
return image;
}
/**
* Crops an image to the specified dimensions
* @param {number} x The x offset
* @param {number} y The y offset
* @param {number} width The new images width
* @param {number} height The new images height
* @returns {Image}
*/
crop(x, y, width, height) {
if (width > this.width) width = this.width;
if (height > this.height) height = this.height;
return this.__apply__(this.__crop__(~~x, ~~y, ~~width, ~~height));
}
/**
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
* @returns {Image}
* @private
*/
__crop__(x, y, width, height) {
x = ~~x;
y = ~~y;
const image = new this.constructor(width, height);
for (let tY = 0; tY < height; tY++) {
const idx = (tY + y) * this.width + x;
image.__u32__.set(this.__u32__.subarray(idx, idx + width), tY * width);
}
return image;
}
/**
* Draws a box at the specified coordinates
* @param {number} x The x offset
* @param {number} y The y offset
* @param {number} width The box width
* @param {number} height The box height
* @param {number|colorFunction} color The color to fill the box in with
* @returns {Image}
*/
drawBox(x, y, width, height, color) {
x = ~~(x - 1);
y = ~~(y - 1);
width = ~~width;
height = ~~height;
if (typeof color === 'function') {
for (let tY = 1; tY <= height; tY++) {
for (let tX = 1; tX <= width; tX++) {
const nX = tX + x;
const nY = tY + y;
if (Math.min(nX, nY) < 1 || nX > this.width || nY > this.height)
continue;
const tC = color(tX, tY);
this.__set_pixel__(nX, nY, tC);
}
}
} else return this.__fast_box__(x, y, width, height, color);
return this;
}
/**
* @private
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
* @param {number} color
*/
__fast_box__(x, y, width, height, color) {
if (x < 0) {
width += x;
x = 0;
}
if (y < 0) {
height += y;
y = 0;
}
const right = Math.max(Math.min(x + width, this.width), 1);
let xPos = right;
while (x <= --xPos)
this.__view__.setUint32(4 * (xPos + y * this.width), color);
const end = 4 * (right + y * this.width);
const start = 4 * (x + y * this.width);
let bottom = Math.max(Math.min(y + height, this.height), 1);
while (y < --bottom)
this.bitmap.copyWithin(4 * (x + bottom * this.width), start, end);
return this;
}
/**
* Draws a circle at the specified coordinates with the specified radius
* @param {number} x The center x position
* @param {number} y The center y position
* @param {number} radius The circles radius
* @param {number|colorFunction} color
* @returns {Image}
*/
drawCircle(x, y, radius, color) {
const radSquared = radius ** 2;
for (let currentY = Math.max(1, y - radius); currentY <= Math.min(y + radius, this.height); currentY++) {
for (let currentX = Math.max(1, x - radius); currentX <= Math.min(x + radius, this.width); currentX++) {
if ((currentX - x) ** 2 + (currentY - y) ** 2 < radSquared)
this.__set_pixel__(currentX, currentY, typeof color === 'function' ? color(currentX - x + radius, currentY - y + radius) : color);
}
}
return this;
}
/**
* Crops the image into a circle
* @param {boolean} [max=false] Whether to use the larger dimension for the size
* @param {number} [feathering=0] How much feathering to apply to the edges
* @returns {Image}
*/
cropCircle(max = false, feathering = 0) {
new v2(this.width, this.height, this.bitmap).crop('circle', feathering);
return this;
}
/**
* Sets the images opacity
* @param {number} opacity The opacity to apply (0..1)
* @param {boolean} absolute Whether to scale the current opacity (false) or just set the new opacity (true)
* @returns {Image}
*/
opacity(opacity, absolute = false) {
if (isNaN(opacity) || opacity < 0)
throw new RangeError('Invalid opacity value');
this.__set_channel_value__(opacity, absolute, 3);
return this;
}
/**
* Sets the red channels saturation
* @param {number} saturation The saturation to apply (0..1)
* @param {boolean} absolute Whether to scale the current saturation (false) or just set the new saturation (true)
* @returns {Image}
*/
red(saturation, absolute = false) {
if (isNaN(saturation) || saturation < 0)
throw new RangeError('Invalid saturation value');
this.__set_channel_value__(saturation, absolute, 0);
return this;
}
/**
* Sets the green channels saturation
* @param {number} saturation The saturation to apply (0..1)
* @param {boolean} absolute Whether to scale the current saturation (false) or just set the new saturation (true)
* @returns {Image}
*/
green(saturation, absolute = false) {
if (isNaN(saturation) || saturation < 0)
throw new RangeError('Invalid saturation value');
this.__set_channel_value__(saturation, absolute, 1);
return this;
}
/**
* Sets the blue channels saturation
* @param {number} saturation The saturation to apply (0..1)
* @param {boolean} absolute Whether to scale the current saturation (false) or just set the new saturation (true)
* @returns {Image}
*/
blue(saturation, absolute = false) {
if (isNaN(saturation) || saturation < 0)
throw new RangeError('Invalid saturation value');
this.__set_channel_value__(saturation, absolute, 2);
return this;
}
/**
* @private
* @param {number} value
* @param {boolean} absolute
* @param {number} offset
*/
__set_channel_value__(value, absolute, offset) {
for (let i = offset; i < this.bitmap.length; i += 4)
this.bitmap[i] = value * (absolute ? 255 : this.bitmap[i]);
}
/**
* Sets the brightness of the image
* @param {number} value The lightness to apply (0..1)
* @param {boolean} absolute Whether to scale the current lightness (false) or just set the new lightness (true)
* @returns {Image}
*/
lightness(value, absolute = false) {
if (isNaN(value) || value < 0)
throw new RangeError('Invalid lightness value');
return this.fill((x, y) => {
const [h, s, l, a] = Image.rgbaToHSLA(...this.getRGBAAt(x, y));
return Image.hslaToColor(h, s, value * (absolute ? 1 : l), a);
});
}
/**
* Sets the saturation of the image
* @param {number} value The saturation to apply (0..1)
* @param {boolean} absolute Whether to scale the current saturation (false) or just set the new saturation (true)
* @returns {Image}
*/
saturation(value, absolute = false) {
if (isNaN(value) || value < 0)
throw new RangeError('Invalid saturation value');
return this.fill((x, y) => {
const [h, s, l, a] = Image.rgbaToHSLA(...this.getRGBAAt(x, y));
return Image.hslaToColor(h, value * (absolute ? 1 : s), l, a);
});
}
/**
* Composites (overlays) the source onto this image at the specified coordinates
* @param {Image} source The image to place
* @param {number} [x=0] The x position to place the image at
* @param {number} [y=0] The y position to place the image at
* @returns {Image}
*/
composite(source, x = 0, y = 0) {
new v2(this.width, this.height, this.bitmap).overlay(new v2(source.width, source.height, source.bitmap), x, y);
return this;
}
/**
* Inverts the images colors
* @returns {Image}
*/
invert() {
for (const [x, y, color] of this.iterateWithColors())
this.__set_pixel__(x, y, ((0xffffffff - color) & 0xffffff00) | (color & 0xff));
return this;
}
/**
* Inverts the images value (lightness)
* @returns {Image}
*/
invertValue() {
for (const [x, y, color] of this.iterateWithColors()) {
const [h, s, l, a] = Image.rgbaToHSLA(...Image.colorToRGBA(color));
this.__set_pixel__(x, y, Image.hslaToColor(h, s, 1 - l, a));
}
return this;
}
/**
* Inverts the images saturation
* @returns {Image}
*/
invertSaturation() {
for (const [x, y, color] of this.iterateWithColors()) {
const [h, s, l, a] = Image.rgbaToHSLA(...Image.colorToRGBA(color));
this.__set_pixel__(x, y, Image.hslaToColor(h, 1 - s, l, a));
}
return this;
}
/**
* Inverts the images hue
* @returns {Image}
*/
invertHue() {
for (const [x, y, color] of this.iterateWithColors()) {
const [h, s, l, a] = Image.rgbaToHSLA(...Image.colorToRGBA(color));
this.__set_pixel__(x, y, Image.hslaToColor(1 - h, s, l, a));
}
return this;
}
/**
* Shifts the images hue
* @param {number} degrees How many degrees to shift the hue by
*/
hueShift(degrees) {
for (const [x, y, color] of this.iterateWithColors()) {
const [h, s, l, a] = Image.rgbaToHSLA(...Image.colorToRGBA(color));
this.__set_pixel__(x, y, Image.hslaToColor(h + degrees / 360, s, l, a));
}
return this;
}
/**
* Gets the average color of the image
* @returns {number}
*/
averageColor() {
let colorAvg = [0, 0, 0];
let divisor = 0;
for (let idx = 0; idx < this.bitmap.length; idx += 4) {
const rgba = this.bitmap.subarray(idx, idx + 4);
for (let i = 0; i < 3; i++)
colorAvg[i] += rgba[i];
divisor += rgba[3] / 255;
}
return Image.rgbaToColor(...colorAvg.map(v => v / divisor), 0xff);
}
/**
* Gets the images dominant color
* @param {boolean} [ignoreBlack=true] Whether to ignore dark colors below the threshold
* @param {boolean} [ignoreWhite=true] Whether to ignore light colors above the threshold
* @param {number} [bwThreshold=0xf] The black/white threshold (0-64)
* @return {number} The images dominant color
*/
dominantColor(ignoreBlack = true, ignoreWhite = true, bwThreshold = 0xf) {
const colorCounts = new Array(0x3ffff);
for (let i = 0; i < this.bitmap.length; i += 4) {
const color = this.__view__.getUint32(i, false);
const [h, s, l] = Image.rgbaToHSLA(...Image.colorToRGBA(color)).map(v => (~~(v * 0x3f)));
if (ignoreBlack && l < bwThreshold) continue;
if (ignoreWhite && l > 0x3f - bwThreshold) continue;
const key = h << 12 | s << 6 | l;
colorCounts[key] = (colorCounts[key] || 0) + 1;
}
let maxColorCount = -1;
let mostProminentValue = 0;
colorCounts.forEach((el, i) => {
if (el < maxColorCount) return;
maxColorCount = el;
mostProminentValue = i;
});
if (mostProminentValue === -1)
return this.dominantColor(ignoreBlack, ignoreWhite, bwThreshold - 1);
const h = (mostProminentValue >>> 12) & 0x3f;
const s = (mostProminentValue >>> 6) & 0x3f;
const l = mostProminentValue & 0x3f;
return Image.hslaToColor(h / 0x3f, s / 0x3f, l / 0x3f, 1);
}
/**
* Rotates the image the given amount of degrees
* @param {number} angle The angle to rotate the image for (in degrees)
* @param {boolean} resize Whether to resize the image so it fits all pixels or just ignore outlying pixels
*/
rotate(angle, resize = true) {
const frame = new v2(this.width, this.height, this.bitmap).rotate(360 - (angle % 360), resize);
const out = new Image(frame.width, frame.height);
out.bitmap.set(frame.u8);
return this.__apply__(out);
}
/**
* Flips / mirrors the image horizontally or vertically
* @param {'horizontal' | 'vertical'} direction The direction to flip
*/
flip(direction) {
const frame = new v2(this.width, this.height, this.bitmap).flip(direction);
this.bitmap.set(frame.u8);
return this;
}
/**
* @private
* @param {Image|Frame} image
* @returns {Image|Frame}
*/
__apply__(image) {
this.__width__ = image.__width__;
this.__height__ = image.__height__;
this.__view__ = image.__view__;
this.__u32__ = image.__u32__;
this.bitmap = image.bitmap;
if (image instanceof Frame)
return Frame.from(this, image.duration, image.xOffset, image.yOffset, image.disposalMode);
return this;
}
/**
* Creates a multi-point gradient generator
* @param {Object<number, number>} colors The gradient points to use (e.g. `{0: 0xff0000ff, 1: 0x00ff00ff}`)
* @return {(function(number): number)} The gradient generator. The function argument is the position in the gradient (0..1).
*/
static gradient(colors) {
const entries = Object.entries(colors).sort((a, b) => a[0] - b[0]);
const positions = entries.map(e => parseFloat(e[0]));
const values = entries.map(e => e[1]);
if (positions.length === 0) throw new RangeError('Invalid gradient point count');
else if (positions.length === 1) {
return () => values[0];
} else if (positions.length === 2) {
const gradient = this.__gradient__(values[0], values[1]);
return position => {
if (position <= positions[0]) return values[0];
if (position >= positions[1]) return values[1];
return gradient((position - positions[0]) / (positions[1] - positions[0]));
};
}
const minDef = Math.min(...positions);
const maxDef = Math.max(...positions);
let gradients = [];
for (let i = 0; i < positions.length; i++) {
let minPos = positions[i - 1];
if (minPos === undefined) continue;
let maxPos = positions[i];
let minVal = values[i - 1];
if (minVal === undefined) minVal = values[i];
const maxVal = values[i];
const gradient = this.__gradient__(minVal, maxVal);
gradients.push({min: minPos, max: maxPos, gradient});
}
return position => {
if (position <= minDef) return gradients[0].gradient(0);
if (position >= maxDef) return gradients[gradients.length - 1].gradient(1);
for (const gradient of gradients)
if (position >= gradient.min && position <= gradient.max)
return gradient.gradient((position - gradient.min) / (gradient.max - gradient.min));
throw new RangeError(`Invalid gradient position: ${position}`);
};
}
/**
* Rounds the images corners
* @param {number} [radius=min(width,height)/4] The radius of the corners
* @return {Image}
*/
roundCorners(radius = Math.min(this.width, this.height) / 4) {
const radSquared = radius ** 2;
for (let x = 1; x <= radius; x++) {
const xRad = (x - radius) ** 2;
for (let y = 1; y <= radius; y++) {
if (xRad + (y - radius) ** 2 > radSquared)
this.bitmap[((y - 1) * this.width + x - 1) * 4 + 3] = 0;
}
}
for (let x = 1; x <= radius; x++) {
const xRad = (x - radius) ** 2;
for (let y = this.height - radius; y <= this.height; y++) {
if (xRad + ((this.height - y) - radius) ** 2 > radSquared)
this.bitmap[((y - 1) * this.width + x - 1) * 4 + 3] = 0;
}
}
for (let x = this.width - radius; x <= this.width; x++) {
const xRad = ((this.width - x) - radius) ** 2;
for (let y = 1; y <= radius; y++) {
if (xRad + (y - radius) ** 2 > radSquared)
this.bitmap[((y - 1) * this.width + x - 1) * 4 + 3] = 0;
}
}
for (let x = this.width - radius; x <= this.width; x++) {
const xRad = ((this.width - x) - radius) ** 2;
for (let y = this.height - radius; y <= this.height; y++) {
if (xRad + ((this.height - y) - radius) ** 2 > radSquared)
this.bitmap[((y - 1) * this.width + x - 1) * 4 + 3] = 0;
}
}
return this;
}
/**
* @private
*/
static __gradient__(startColor, endColor) {
const sr = startColor >>> 24;
const sg = startColor >> 16 & 0xff;
const sb = startColor >> 8 & 0xff;
const sa = startColor & 0xff;
const er = (endColor >>> 24) - sr;
const eg = (endColor >> 16 & 0xff) - sg;
const eb = (endColor >> 8 & 0xff) - sb;
const ea = (endColor & 0xff) - sa;
return position => {
const r = sr + position * er;
const g = sg + position * eg;
const b = sb + position * eb;
const a = sa + position * ea;
return (((r & 0xff) << 24) | ((g & 0xff) << 16) | ((b & 0xff) << 8) | (a & 0xff));
};
}
fisheye(radius = 2) {
const r = new Image(this.width, this.height);
const w = this.width;
const h = this.height;
const tu32 = this.__u32__;
const ru32 = r.__u32__;
const iw = 1 / w;
const ih = 1 / h;
for (const [x, y] of this) {
const xco = x * iw - .5;
const yco = y * ih - .5;
const dfc = Math.sqrt(xco ** 2 + yco ** 2);
const dis = 2 * dfc ** radius;
const nx = ((dis * xco / dfc + 0.5) * w) | 0;
const ny = ((dis * yco / dfc + 0.5) * h) | 0;
if (nx < 1 || nx > w || ny < 1 || ny > h || isNaN(nx) || isNaN(ny))
continue;
ru32[y * w + x] = tu32[w * ny + nx];
}