Repository navigation
Expand file tree
/
Copy pathimage.ts
More file actions
2574 lines (2290 loc) · 107 KB
/
Copy pathimage.ts
File metadata and controls
2574 lines (2290 loc) · 107 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 * as png from './codecs/png.ts';
import * as jpeg from './codecs/jpeg.ts';
import * as tiff from './codecs/tiff.ts';
import * as webp from './codecs/webp.ts';
import * as tga from './codecs/tga.ts';
import * as bmp from './codecs/bmp.ts';
import * as ico from './codecs/ico.ts';
import * as qoi from './codecs/qoi.ts';
import * as netpbm from './codecs/netpbm.ts';
import * as hdr from './codecs/hdr.ts';
import * as avif from './codecs/avif.ts';
import * as avifEnc from './codecs/avif-enc.ts';
import * as jxl from './codecs/jxl.ts';
import type { ToneMapping } from './codecs/hdr.ts';
import * as quantize from './codecs/quantize.ts';
import * as textRenderer from './render/text.ts';
import * as svgRenderer from './render/svg.ts';
import { BinaryData, view } from './util/mem.ts';
import { ImageType } from './image-type.ts';
import { TextLayout } from './text-layout.ts';
import { Metadata, resolveMetadata, pngText, exifData } from './metadata.ts';
import { encode as utf8 } from './util/utf8.ts';
import { resample, BOX, TRIANGLE, CUBIC } from './util/resample.ts';
import { rotateBilinear } from './util/rotate.ts';
import { gaussianBlur, boxBlurRGBA, premultiply, unpremultiply } from './util/blur.ts';
import { isOptions, finite, color as checkColor } from './util/options.ts';
import { MAX_PIXELS, decoding } from './util/limits.ts';
/** A color as a 32-bit RGBA integer (`0xRRGGBBAA`) */
export type Color = number;
/** Called with a pixel's (0-based) coordinates, returns its color */
export type ColorFunction = (x: number, y: number) => Color;
/** Resampling filters for {@link Image.resize} and the other scaling functions, see {@link Image.RESIZE_BILINEAR} etc. */
export type ResizeMode = 'RESIZE_NEAREST_NEIGHBOR' | 'RESIZE_BILINEAR' | 'RESIZE_BICUBIC' | 'RESIZE_AREA';
/** How {@link Image.renderSVG} scales: {@link Image.SVG_MODE_SCALE}, {@link Image.SVG_MODE_WIDTH} or {@link Image.SVG_MODE_HEIGHT} */
export type SVGScaleMode = 1 | 2 | 3;
/** Blend modes of {@link Image.composite}, named like CSS' mix-blend-mode values */
export type BlendMode = 'normal' | 'multiply' | 'screen' | 'overlay' | 'darken' | 'lighten' | 'color-dodge' | 'color-burn'
| 'hard-light' | 'soft-light' | 'difference' | 'exclusion' | 'add';
/** Options of {@link Image.composite} */
export interface CompositeOptions {
/** The x position to place the source at, if the options are the second argument. Default: `0` */
x?: number;
/** The y position to place the source at, if the options are the second argument. Default: `0` */
y?: number;
/** Opacity of the source (0..1). Default: `1` */
opacity?: number;
/** How the colors are mixed. Default: `'normal'` */
mode?: BlendMode;
}
/** Options of {@link Image.scale}, {@link Image.resize}, {@link Image.contain}, {@link Image.fit} and {@link Image.cover} */
export interface ResizeOptions {
/** The resizing mode. Default: {@link Image.RESIZE_BILINEAR} */
mode?: ResizeMode;
/**
* Whether to round to 8 bits between the two passes, so two channels share the multiplications of both: about
* 15-25% faster for opaque images, with 10-25% of the channel values a step off the precise result (instead of
* about 1%, never more than 1). Transparent images are premultiplied to 8 bits like browsers do, which makes them
* about twice as fast: what shows once they're composited differs by up to about 2 steps, pixels that are almost
* transparent keep less of their color. Only affects {@link Image.RESIZE_BILINEAR} and {@link Image.RESIZE_AREA},
* down to about a third of the size. Default: `true`
*/
fast?: boolean;
}
/**
* Options of {@link Image.opacity}, {@link Image.red}, {@link Image.green}, {@link Image.blue}, {@link Image.lightness}
* and {@link Image.saturation}
*/
export interface AdjustOptions {
/** Whether to set the value (true) or scale the current one (false). Default: `false` */
absolute?: boolean;
}
/** Options of {@link Image.sharpen} */
export interface SharpenOptions {
/** How strongly to sharpen (0 does nothing). Default: `1` */
amount?: number;
/** The radius of the blur the image is compared with (larger values sharpen coarser details). Default: `1` */
radius?: number;
}
/** Options of {@link Image.encode} */
export interface PNGEncodeOptions {
/** The compression level (0-9). Default: `1` */
compression?: number;
/** Metadata to include, see {@link Metadata} */
metadata?: Metadata;
}
/** Options of {@link Image.encodeJPEG} */
export interface JPEGEncodeOptions {
/** The JPEG quality (1-100), chroma subsampling is disabled above 90. Default: `90` */
quality?: number;
/** Metadata to include, see {@link Metadata} */
metadata?: Metadata;
}
/** Options of {@link Image.encodeWebP} */
export interface WebPEncodeOptions {
/**
* Lossy compression (0-100, like libwebp's quality: 75 is its default): the image is encoded like cwebp encodes it
* (with `-m` set to the effort), much smaller than lossless. Without it the image is encoded losslessly
*/
quality?: number;
/**
* How much effort lossy compression takes (0-6, libwebp's method): higher is smaller but slower. 0-2 pick the
* predictions by how close they are, 3 and up also by how many bits they take, 5 and 6 also optimize the
* quantized values. Default: `2`: about a quarter of the time of 4 (cwebp's default) for files about 5% larger
*/
effort?: number;
/** Metadata to include, see {@link Metadata} */
metadata?: Metadata;
}
/** Options of {@link Image.encodeTGA} */
export interface EncodeOptions {
/** Metadata to include, see {@link Metadata} */
metadata?: Metadata;
}
/** Options of {@link Image.roundCorners} */
export interface RoundCornersOptions {
/** The radius of the corners. Default: a quarter of the smaller side */
radius?: number;
}
/** Options of {@link Image.fisheye} */
export interface FisheyeOptions {
/** The distortion strength (exponent of the radial mapping), higher values bulge the center more. Default: `2` */
strength?: number;
}
/** Options of {@link Image.renderSVG} */
export interface SVGOptions {
/** The scale, or the width or height in pixels, see `mode`. Default: `1` */
size?: number;
/**
* What `size` is: one of {@link Image.SVG_MODE_SCALE}, {@link Image.SVG_MODE_WIDTH}, {@link Image.SVG_MODE_HEIGHT}.
* Default: {@link Image.SVG_MODE_SCALE}
*/
mode?: SVGScaleMode;
}
/** Options of {@link Image.renderText}: the text color and layout, and its style (see {@link TextStyle}) */
export interface TextOptions extends TextStyle {
/** The text color. Default: `0xffffffff` */
color?: Color;
/** The text layout. Default: `new TextLayout()` */
layout?: TextLayout;
}
/** Options of {@link Image.decode} */
export interface DecodeOptions {
/** Whether to rotate/mirror JPEGs, TIFFs, PNGs and WebPs as their orientation tag (Exif or XMP) says. Default: `true` */
applyOrientation?: boolean;
/**
* The most pixels to decode: larger images throw a RangeError before anything that size is allocated, so small
* files declaring huge images (decompression bombs) can't exhaust the memory. Default: `268402689` (16383², like
* sharp), `Infinity` for no limit
*/
maxPixels?: number;
/**
* How Radiance HDRs, PFMs and HDR (PQ or HLG) AVIFs and JPEG XLs, whose light can be brighter than (SDR) white,
* become 8 bit sRGB: `'reinhard'` compresses the brightest parts like Reinhard's tone mapping operator does (the
* brightest pixel becomes white, images no brighter than white stay as they are), `'clamp'` clamps everything
* brighter than white. Default: `'reinhard'`
*/
toneMapping?: ToneMapping;
}
/** Options of {@link Image.encodeJXL} */
export interface JXLEncodeOptions {
/**
* Lossy compression (0-100, like cjxl's `-q`: 90 is visually lossless, 100 lossless): higher is better and larger.
* Without it the image is encoded losslessly
*/
quality?: number;
/**
* How hard lossy compression searches for the best transforms: 0-2, faster to smaller. 0 uses 8x8 DCTs only (like
* `cjxl -e 3`), 1 and 2 search their sizes like `cjxl -e 5` (2 tries more of the small ones). Default: `1`
*/
effort?: number;
/** Metadata to include, see {@link Metadata} */
metadata?: Metadata;
}
/** Options of {@link Image.encodeAVIF} */
export interface AVIFEncodeOptions {
/** 0-100, like avifenc's: higher is better and larger, 100 is lossless. Default: `60` */
quality?: number;
/** The quality of the alpha channel (if the image has transparency), like avifenc's. Default: `100` (lossless) */
alphaQuality?: number;
/** Chroma subsampling: `'4:4:4'` keeps the full color resolution, `'4:2:0'` halves it (smaller). Default: `'4:4:4'` */
subsampling?: '4:4:4' | '4:2:0';
/** How hard the encoder searches for the best modes: 0-2, faster to smaller. Default: `1` */
effort?: number;
/** Metadata to include, see {@link Metadata} */
metadata?: Metadata;
}
/** Text style options of {@link Image.renderText} */
export interface TextStyle {
/** Width of an outline around the glyphs in pixels. Default: `0` */
strokeWidth?: number;
/** Color of the outline. Default: `0x000000ff` */
strokeColor?: Color;
/**
* Whether to run the hinting instructions of TrueType fonts, which align stems and edges with the pixel grid for
* crisper text at small sizes (like Windows renders text); the glyphs of hinted fonts are then placed on whole
* pixels. Fonts without instructions (and CFF/OpenType outlines) aren't affected. Default: `true`
*/
hinting?: boolean;
}
/** Options of {@link Image.cropCircle} */
export interface CropCircleOptions {
/** Whether to use the larger dimension for the size. Default: `false` */
max?: boolean;
/** Share of the radius (0..1) over which the edge fades out. Default: `0` */
feathering?: number;
}
/** Options of {@link Image.dominantColor} */
export interface DominantColorOptions {
/** Whether to ignore dark colors (all channels below the threshold). Default: `true` */
ignoreBlack?: boolean;
/** Whether to ignore light colors (all channels above 255 minus the threshold). Default: `true` */
ignoreWhite?: boolean;
/** The black/white threshold (0-64, in steps of 4 channel values). Default: `15` */
threshold?: number;
}
/** Options of {@link Image.rotate} */
export interface RotateOptions {
/** Whether to resize the image so it fits all pixels or just ignore outlying pixels. Default: `true` */
resize?: boolean;
/**
* Whether to sample with 8-bit weights on 8-bit premultiplied pixels (like {@link ResizeOptions.fast}), about twice
* as fast: opaque pixels stay within a step of the precise result, what shows of translucent ones (also the
* faded edges) within about 2.5 steps (pixels that are almost transparent keep less of their color). Only affects
* angles that aren't multiples of 90°. Default: `true`
*/
fast?: boolean;
}
/** Options of {@link Image.trim} */
export interface TrimOptions {
/**
* How far (0-1) a pixel's channels may be from the color for it to be trimmed, e.g. for JPEG artifacts or
* antialiasing. Default: `0`
*/
tolerance?: number;
}
/** Options of {@link Image.colorToAlpha} */
export interface ColorToAlphaOptions {
/** Pixels at most this far from the color (0-1) become fully transparent. Default: 0 */
transparencyThreshold?: number;
/** Pixels at least this far from the color (0-1) stay fully opaque. Default: 1 */
opacityThreshold?: number;
}
/**
* Text metadata written into PNGs
* @deprecated Use {@link Metadata}, which all encoders take
*/
export type PNGMetadata = Metadata;
/**
* An RGBA image; provides the codecs and the manipulation functions. Methods that change the image modify it in place
* and return it, so calls can be chained
*/
export class Image {
/**
* @internal
* @ignore
*/
protected __width__: number;
/**
* @internal
* @ignore
*/
protected __height__: number;
/**
* @internal
* @ignore
*/
protected __view__!: DataView;
/**
* @internal
* @ignore
*/
protected __u32__!: Uint32Array;
/**
* @internal
* @ignore
*/
protected __bitmap__!: Uint8ClampedArray;
/**
* Creates a new image with the given dimensions
* @param width
* @param height
*/
constructor(width: number, height: number) {
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');
this.__width__ = width;
this.__height__ = height;
this.__set_bitmap__(new Uint8ClampedArray(width * height * 4));
}
/**
* The image's RGBA pixel data. It can be replaced by any 8-bit array with width * height * 4 bytes
* (it is used as is, without copying)
*/
get bitmap(): Uint8ClampedArray {
return this.__bitmap__;
}
/** Replaces the pixel data, the array has to hold width * height * 4 bytes */
set bitmap(bitmap: Uint8ClampedArray | Uint8Array) {
if (!(bitmap instanceof Uint8ClampedArray || bitmap instanceof Uint8Array))
throw new TypeError('The bitmap has to be a Uint8ClampedArray or Uint8Array');
if (bitmap.length !== this.width * this.height * 4)
throw new RangeError(`The bitmap has to have ${this.width * this.height * 4} bytes (width * height * 4), got ${bitmap.length}`);
this.__set_bitmap__(bitmap instanceof Uint8ClampedArray ? bitmap : new Uint8ClampedArray(bitmap.buffer, bitmap.byteOffset, bitmap.length));
}
/**
* Sets the pixel data and the views on it
* @internal
* @ignore
*/
protected __set_bitmap__(bitmap: Uint8ClampedArray): void {
// 32-bit views need an aligned offset
if (bitmap.byteOffset % 4) bitmap = bitmap.slice();
this.__bitmap__ = bitmap;
this.__view__ = new DataView(bitmap.buffer, bitmap.byteOffset, bitmap.byteLength);
this.__u32__ = new Uint32Array(bitmap.buffer, bitmap.byteOffset, bitmap.length >> 2);
}
/** A short description for debugging, e.g. `Image<64x64>` */
toString(): string {
return `Image<${this.width}x${this.height}>`;
}
/**
* The images width
*/
get width(): number {
return this.__width__;
}
/**
* The images height
*/
get height(): number {
return this.__height__;
}
/**
* Yields an [x, y] array for every pixel in the image (0-based)
* @yields The coordinates of the pixel ([x, y])
*/
*[Symbol.iterator](): Generator<[x: number, y: number], void, undefined> {
for (let y = 0; y < this.height; y++)
for (let x = 0; x < this.width; x++)
yield [x, y];
}
/**
* Yields an [x, y, color] array for every pixel in the image (0-based)
* @yields The coordinates and color of the pixel ([x, y, color])
*/
*iterateWithColors(): Generator<[x: number, y: number, color: Color], void, undefined> {
const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength);
let offset = 0;
for (let y = 0; y < this.height; y++)
for (let x = 0; x < this.width; x++, offset += 4)
yield [x, y, view.getUint32(offset, false)];
}
/**
* Converts RGBA components to an RGBA value, values are rounded and clamped to 0..255
* @param r red (0..255)
* @param g green (0..255)
* @param b blue (0..255)
* @param a alpha (0..255)
* @returns RGBA value
*/
static rgbaToColor(r: number, g: number, b: number, a: number): Color {
r = finite(r, 'red');
g = finite(g, 'green');
b = finite(b, 'blue');
a = finite(a, 'alpha');
return (channel(r) << 24 | channel(g) << 16 | channel(b) << 8 | channel(a)) >>> 0;
}
/**
* Converts RGB components to an RGBA value (assuming alpha = 255)
* @param r red (0..255)
* @param g green (0..255)
* @param b blue (0..255)
* @returns RGBA value
*/
static rgbToColor(r: number, g: number, b: number): Color {
return Image.rgbaToColor(r, g, b, 0xff);
}
/**
* Converts HSLA colors to RGBA colors
* @param h hue (0..1)
* @param s saturation (0..1)
* @param l lightness (0..1)
* @param a opacity (0..1)
* @returns color
*/
static hslaToColor(h: number, s: number, l: number, a: number): Color {
h = wrapHue(finite(h, 'hue'));
s = finite(s, 'saturation');
l = finite(l, 'lightness');
a = finite(a, 'alpha');
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: number, g: number, b: number;
if (s === 0) {
r = g = b = l;
} else {
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(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), Math.round(a * 255));
}
/**
* Converts HSL colors to RGBA colors (assuming an opacity of 255)
* @param h hue (0..1)
* @param s saturation (0..1)
* @param l lightness (0..1)
* @returns color
*/
static hslToColor(h: number, s: number, l: number): Color {
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 The HSLA values ([H, S, L, A])
*/
static rgbaToHSLA(r: number, g: number, b: number, a: number): [h: number, s: number, l: number, a: number] {
r = finite(r, 'red') / 255;
g = finite(g, 'green') / 255;
b = finite(b, 'blue') / 255;
a = finite(a, 'alpha');
const max = Math.max(r, g, b), min = Math.min(r, g, b);
let h = 0, s: number;
const 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 color The color value to convert
* @returns The RGBA values ([R, G, B, A])
*/
static colorToRGBA(color: Color): [r: number, g: number, b: number, a: number] {
color = checkColor(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 color The color value to convert
* @returns The RGB values ([R, G, B])
*/
static colorToRGB(color: Color): [r: number, g: number, b: number] {
const [r, g, b] = Image.colorToRGBA(color);
return [r, g, b];
}
/**
* Gets the pixel color at the specified position (0-based)
* @param x
* @param y
* @returns The color value
*/
getPixelAt(x: number, y: number): Color {
x = ~~finite(x, 'x');
y = ~~finite(y, 'y');
this.__check_boundaries__(x, y);
return this.__view__.getUint32((y * this.width + x) * 4, false);
}
/**
* Gets a view of the RGBA components of the pixel at the specified position (0-based)
* @param x
* @param y
* @returns The RGBA value
*/
getRGBAAt(x: number, y: number): Uint8ClampedArray {
x = ~~finite(x, 'x');
y = ~~finite(y, 'y');
this.__check_boundaries__(x, y);
const idx = (y * this.width + x) * 4;
return this.bitmap.subarray(idx, idx + 4);
}
/**
* Sets the pixel color for the specified position (0-based)
* @param x
* @param y
* @param pixelColor
*/
setPixelAt(x: number, y: number, pixelColor: Color): this {
x = ~~finite(x, 'x');
y = ~~finite(y, 'y');
this.__check_boundaries__(x, y);
this.__set_pixel__(x, y, checkColor(pixelColor));
return this;
}
/**
* @private
* @param x
* @param y
* @param pixelColor
*/
/**
* @internal
* @ignore
*/
protected __set_pixel__(x: number, y: number, pixelColor: Color): void {
this.__view__.setUint32((y * this.width + x) * 4, pixelColor, false);
}
/**
* @private
* @param x
* @param y
*/
/**
* @internal
* @ignore
*/
protected __check_boundaries__(x: number, y: number): void {
if (isNaN(x)) throw new TypeError(`Invalid pixel coordinates (x=${x})`);
if (isNaN(y)) throw new TypeError(`Invalid pixel coordinates (y=${y})`);
if (x < 0)
throw new RangeError(`${Image.__out_of_bounds__} (x=${x})<0`);
if (x >= this.width)
throw new RangeError(`${Image.__out_of_bounds__} (x=${x})>=(width=${this.width})`);
if (y < 0)
throw new RangeError(`${Image.__out_of_bounds__} (y=${y})<0`);
if (y >= this.height)
throw new RangeError(`${Image.__out_of_bounds__} (y=${y})>=(height=${this.height})`);
}
/**
* @private
*/
/**
* @internal
* @ignore
*/
protected static get __out_of_bounds__(): string {
return 'Tried referencing a pixel outside of the images boundaries:';
}
/**
* @callback colorFunction
* @param x 0-based x coordinate
* @param y 0-based y coordinate
* @returns pixel color
*/
/**
* Fills the image data with the supplied color
* @param color
*/
fill(color: Color | ColorFunction): this {
const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength);
if (typeof color === 'function') {
let offset = 0;
for (let y = 0; y < this.height; y++)
for (let x = 0; x < this.width; x++, offset += 4)
view.setUint32(offset, color(x, y), false);
} else {
color = checkColor(color);
if (!this.bitmap.length) return this;
view.setUint32(0, color, false);
const u32 = new Uint32Array(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength / 4);
u32.fill(u32[0]);
}
return this;
}
/**
* Clones the current image
*/
clone(): Image {
// copying in the constructor of the array saves zeroing the memory first
const image = new Image(1, 1);
image.__width__ = this.width;
image.__height__ = this.height;
image.__set_bitmap__(new Uint8ClampedArray(this.bitmap));
return image;
}
/**
* Use {@link https://en.wikipedia.org/wiki/Image_scaling#Nearest-neighbor_interpolation Nearest-neighbor} resizing.
*/
static get RESIZE_NEAREST_NEIGHBOR(): 'RESIZE_NEAREST_NEIGHBOR' {
return 'RESIZE_NEAREST_NEIGHBOR';
}
/**
* Bilinear resizing (the default). When shrinking, the filter widens with the scale factor, so every source pixel contributes
*/
static get RESIZE_BILINEAR(): 'RESIZE_BILINEAR' {
return 'RESIZE_BILINEAR';
}
/**
* Bicubic (Catmull-Rom) resizing, sharper than bilinear, especially when enlarging
*/
static get RESIZE_BICUBIC(): 'RESIZE_BICUBIC' {
return 'RESIZE_BICUBIC';
}
/**
* Area averaging (box filter): every output pixel is the average of the source pixels it covers. Meant for shrinking
*/
static get RESIZE_AREA(): 'RESIZE_AREA' {
return 'RESIZE_AREA';
}
/**
* Used for automatically preserving an images aspect ratio when resizing.
*/
static get RESIZE_AUTO(): -1 {
return -1;
}
/**
* Resizes the image by the given factor
* @param factor The factor to resize the image with
* @param options See {@link ResizeOptions}
*/
scale(factor: number, options?: ResizeOptions): this;
/**
* Resizes the image by the given factor
* @param factor The factor to resize the image with
* @param [mode=Image.RESIZE_BILINEAR] The resizing mode to use
*/
scale(factor: number, mode?: ResizeMode): this;
scale(factor: number, modeOrOptions?: ResizeMode | ResizeOptions): this {
const { mode, fast } = resizeOptions(modeOrOptions);
const image = this.__scale__(factor, mode, fast);
return this.__apply__(image);
}
/** @private */
/**
* @internal
* @ignore
*/
protected __scale__(factor: number, mode: ResizeMode = Image.RESIZE_BILINEAR, fast = true): Image {
if (factor === 1) return this;
return this.__resize__(this.width * factor, this.height * factor, mode, fast);
}
/**
* Resizes the image to the given dimensions.
* Use {@link Image.RESIZE_AUTO} as either width or height to automatically preserve the aspect ratio.
* @param width The new width
* @param height The new height
* @param options See {@link ResizeOptions}
* @returns The resized image
*/
resize(width: number, height: number, options?: ResizeOptions): this;
/**
* Resizes the image to the given dimensions.
* Use {@link Image.RESIZE_AUTO} as either width or height to automatically preserve the aspect ratio.
* @param width The new width
* @param height The new height
* @param [mode=Image.RESIZE_BILINEAR] The resizing mode to use
* @returns The resized image
*/
resize(width: number, height: number, mode?: ResizeMode): this;
resize(width: number, height: number, modeOrOptions?: ResizeMode | ResizeOptions): this {
const { mode, fast } = resizeOptions(modeOrOptions);
const image = this.__resize__(width, height, mode, fast);
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 width The width of the bounding box
* @param height The height of the bounding box
* @param options See {@link ResizeOptions}
* @returns The resized image
*/
contain(width: number, height: number, options?: ResizeOptions): this;
/**
* 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 width The width of the bounding box
* @param height The height of the bounding box
* @param [mode=Image.RESIZE_BILINEAR] The resizing mode to use
* @returns The resized image
*/
contain(width: number, height: number, mode?: ResizeMode): this;
contain(width: number, height: number, modeOrOptions?: ResizeMode | ResizeOptions): this {
const options = resizeOptions(modeOrOptions);
width = Math.floor(finite(width, 'width'));
height = Math.floor(finite(height, 'height'));
// round instead of flooring the scaled size, so the limiting axis matches the box exactly
const scale = Math.min(width / this.width, height / this.height);
return this.resize(Math.max(1, Math.min(width, Math.round(this.width * scale))), Math.max(1, Math.min(height, Math.round(this.height * scale))), options);
}
/**
* 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 width The width of the bounding box
* @param height The height of the bounding box
* @param options See {@link ResizeOptions}
* @returns The resized image
*/
fit(width: number, height: number, options?: ResizeOptions): this;
/**
* 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 width The width of the bounding box
* @param height The height of the bounding box
* @param [mode=Image.RESIZE_BILINEAR] The resizing mode to use
* @returns The resized image
*/
fit(width: number, height: number, mode?: ResizeMode): this;
fit(width: number, height: number, modeOrOptions?: ResizeMode | ResizeOptions): this {
const options = resizeOptions(modeOrOptions);
const result = new Image(width, height);
this.contain(width, height, options);
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 width The width of the bounding box
* @param height The height of the bounding box
* @param options See {@link ResizeOptions}
* @returns The resized image
*/
cover(width: number, height: number, options?: ResizeOptions): this;
/**
* Resizes the image so it covers the given bounding box, cropping the overflowing edges.
* Always returns the exact dimensions of the bounding box.
* @param width The width of the bounding box
* @param height The height of the bounding box
* @param [mode=Image.RESIZE_BILINEAR] The resizing mode to use
* @returns The resized image
*/
cover(width: number, height: number, mode?: ResizeMode): this;
cover(width: number, height: number, modeOrOptions?: ResizeMode | ResizeOptions): this {
const options = resizeOptions(modeOrOptions);
width = Math.floor(width);
height = Math.floor(height);
const scale = Math.max(width / this.width, height / this.height);
this.resize(Math.max(width, Math.round(this.width * scale)), Math.max(height, Math.round(this.height * scale)), options);
return this.crop((this.width - width) / 2, (this.height - height) / 2, width, height);
}
/** @private */
/**
* @internal
* @ignore
*/
protected __resize__(width: number, height: number, mode: ResizeMode = Image.RESIZE_BILINEAR, fast = true): Image {
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 = Math.max(1, Math.round(this.width / this.height * Math.floor(height)));
else if (height === Image.RESIZE_AUTO) height = Math.max(1, Math.round(this.height / this.width * Math.floor(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');
if (mode === Image.RESIZE_NEAREST_NEIGHBOR) return this.__resize_nearest_neighbor__(width, height);
const filter = mode === Image.RESIZE_BILINEAR ? TRIANGLE : mode === Image.RESIZE_BICUBIC ? CUBIC : mode === Image.RESIZE_AREA ? BOX : null;
if (!filter) throw new Error('Invalid resize mode');
const image = new Image(width, height);
resample(this.bitmap, this.width, this.height, width, height, filter, image.bitmap, fast);
return image;
}
/**
* @private
* @param width The new width
* @param height The new height
*/
/**
* @internal
* @ignore
*/
protected __resize_nearest_neighbor__(width: number, height: number): Image {
const image = new Image(width, height);
const src = this.__u32__;
const dst = image.__u32__;
// sample at the centers of the output pixels
for (let y = 0; y < height; y++) {
const row = this.width * ((y + 0.5) * (this.height / height) | 0);
for (let x = 0; x < width; x++)
dst[y * width + x] = src[row + ((x + 0.5) * (this.width / width) | 0)];
}
return image;
}
/**
* Crops an image to the specified dimensions.
* The region is clipped to the image, so the result can be smaller than the requested size
* @param x The x offset (0-based)
* @param y The y offset (0-based)
* @param width The new images width
* @param height The new images height
*/
crop(x: number, y: number, width: number, height: number): this {
x = ~~finite(x, 'x');
y = ~~finite(y, 'y');
width = ~~finite(width, 'width');
height = ~~finite(height, 'height');
const left = Math.max(0, x), top = Math.max(0, y);
const right = Math.min(this.width, x + width), bottom = Math.min(this.height, y + height);
if (right <= left || bottom <= top)
throw new RangeError('Crop region does not overlap the image');
return this.__apply__(this.__crop__(left, top, right - left, bottom - top));
}
/**
* Removes borders of one color, e.g. the empty space around rendered text or around a logo on a solid background.
* Frames keep their position: their offsets move by the trimmed amount. An image that only has the color stays
* unchanged
* @param color The border color, by default the color of the top left pixel. Fully transparent pixels count as the
* same color whatever their RGB values
* @param options See {@link TrimOptions}
*/
trim(color?: Color, options: TrimOptions = {}): this {
const bounds = this.__trim_bounds__(color, options);
return bounds ? this.__apply__(this.__crop__(...bounds)) : this;
}
/**
* The area that remains after trimming as [x, y, width, height], null if nothing would remain
* @internal
* @ignore
*/
protected __trim_bounds__(color: Color | undefined, { tolerance = 0 }: TrimOptions): [number, number, number, number] | null {
if (!(tolerance >= 0 && tolerance <= 1)) throw new RangeError('Invalid tolerance, it has to be between 0 and 1');
const bitmap = this.bitmap;
const { width, height } = this;
if (color !== undefined) color = checkColor(color);
const c = color === undefined ? [bitmap[0], bitmap[1], bitmap[2], bitmap[3]] : [color >>> 24, color >> 16 & 255, color >> 8 & 255, color & 255];
const limit = tolerance * 255;
const matches = (x: number, y: number): boolean => {
const i = (y * width + x) * 4;
if (Math.abs(bitmap[i + 3] - c[3]) > limit) return false;
// transparent pixels have no color
if (bitmap[i + 3] === 0 && c[3] === 0) return true;
return Math.abs(bitmap[i] - c[0]) <= limit && Math.abs(bitmap[i + 1] - c[1]) <= limit && Math.abs(bitmap[i + 2] - c[2]) <= limit;
};
const rowMatches = (y: number): boolean => {
for (let x = 0; x < width; x++) if (!matches(x, y)) return false;
return true;
};
const columnMatches = (x: number, top: number, bottom: number): boolean => {
for (let y = top; y < bottom; y++) if (!matches(x, y)) return false;
return true;
};
let top = 0, bottom = height;
while (top < height && rowMatches(top)) top++;
if (top === height) return null;
while (rowMatches(bottom - 1)) bottom--;
let left = 0, right = width;
while (columnMatches(left, top, bottom)) left++;
while (columnMatches(right - 1, top, bottom)) right--;
return [left, top, right - left, bottom - top];
}
/**
* @param x
* @param y
* @param width
* @param height
* @private
*/
/**
* @internal
* @ignore
*/
protected __crop__(x: number, y: number, width: number, height: number): Image {
x = ~~x;
y = ~~y;
const image = new Image(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 (0-based), clipped to the image
* @param x The x offset
* @param y The y offset
* @param width The box width
* @param height The box height
* @param color The color to fill the box in with, a function gets coordinates relative to the box
*/
drawBox(x: number, y: number, width: number, height: number, color: Color | ColorFunction): this {
x = ~~finite(x, 'x');
y = ~~finite(y, 'y');
width = ~~finite(width, 'width');
height = ~~finite(height, 'height');
if (typeof color !== 'function') return this.__fast_box__(x, y, width, height, checkColor(color));
for (let tY = Math.max(0, -y); tY < height && tY + y < this.height; tY++)
for (let tX = Math.max(0, -x); tX < width && tX + x < this.width; tX++)
this.__set_pixel__(tX + x, tY + y, color(tX, tY));
return this;
}
/**