imagescript 4.0.0-rc.5 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/image.js CHANGED
@@ -17,7 +17,7 @@ import * as jxl from "./codecs/jxl.js";
17
17
  import * as quantize from "./codecs/quantize.js";
18
18
  import * as textRenderer from "./render/text.js";
19
19
  import * as svgRenderer from "./render/svg.js";
20
- import { view } from "./util/mem.js";
20
+ import { view, isBinaryData } from "./util/mem.js";
21
21
  import { cicpTransform, colorSpaceTransform, profileTransform } from "./util/icc.js";
22
22
  import { ImageType } from "./image-type.js";
23
23
  import { textLayout } from "./text-layout.js";
@@ -26,8 +26,8 @@ import { encode as utf8 } from "./util/utf8.js";
26
26
  import { resample, BOX, TRIANGLE, CUBIC } from "./util/resample.js";
27
27
  import { gaussianBlur, boxBlurRGBA, premultiply, unpremultiply } from "./util/blur.js";
28
28
  import { Colors, wrapHue, hue2rgb } from "./colors.js";
29
- import { isOptions, checkOptions, finite, nonNegative, positive, unitInterval, oneOf, pixelLimit, checkThreads, gainMapEmbed, boolean, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
30
- import { MAX_PIXELS, LimitError, decoding, checkGrowth } from "./util/limits.js";
29
+ import { allocate, scaleFactor, instance, shown, isOptions, checkOptions, finite, nonNegative, atLeast, positive, pixels, coordinate, cropBounds, unitInterval, oneOf, pixelLimit, checkThreads, gainMapEmbed, boolean, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
30
+ import { MAX_PIXELS, LimitError, decoding, checkGrowth, checkFormatSize } from "./util/limits.js";
31
31
  import { GainMap } from "./gainmap.js";
32
32
  import * as gain from "./util/gain.js";
33
33
  import { multiply, invert } from "./util/matrix.js";
@@ -43,16 +43,16 @@ export const TONE_MAPPINGS = ['reinhard', 'clamp'];
43
43
  export const FLIP_DIRECTIONS = ['horizontal', 'vertical'];
44
44
  function featureList(features) {
45
45
  if (typeof features !== 'object' || features === null)
46
- throw new TypeError('Features must be an object');
46
+ throw new TypeError(`features must be an object, like { liga: false }, not ${shown(features)}`);
47
47
  return Object.entries(features).map(([tag, value]) => {
48
48
  if (!/^[\x20-\x7e]{4}$/.test(tag))
49
- throw new RangeError(`Invalid OpenType feature tag: ${JSON.stringify(tag)}`);
49
+ throw new RangeError(`An OpenType feature tag must be 4 printable ASCII characters, not ${JSON.stringify(tag)}`);
50
50
  if (typeof value === 'boolean')
51
51
  return [tag, value ? 1 : 0];
52
52
  if (typeof value !== 'number')
53
- throw new TypeError(`The value of the OpenType feature ${tag} must be a boolean or a number, not ${value === null ? 'null' : typeof value}`);
53
+ throw new TypeError(`The value of the OpenType feature ${tag} must be a boolean or a number, not ${shown(value)}`);
54
54
  if (!Number.isInteger(value) || value < 0 || value > 255)
55
- throw new RangeError(`Invalid value of the OpenType feature ${tag}: ${value}`);
55
+ throw new RangeError(`The value of the OpenType feature ${tag} must be a whole number from 0 to 255, not ${value}`);
56
56
  return [tag, value];
57
57
  });
58
58
  }
@@ -64,36 +64,27 @@ export class Image {
64
64
  __bitmap__;
65
65
  __gain_map__ = null;
66
66
  constructor(width, height) {
67
- width = Math.trunc(finite(width, 'width'));
68
- height = Math.trunc(finite(height, 'height'));
69
- if (width < 1)
70
- throw new RangeError('Image has to be at least 1 pixel wide');
71
- if (height < 1)
72
- throw new RangeError('Image has to be at least 1 pixel high');
73
- if (width > 0x7fffffff)
74
- throw new RangeError('Image width is too large');
75
- if (height > 0x7fffffff)
76
- throw new RangeError('Image height is too large');
67
+ width = pixels(width, 'width');
68
+ height = pixels(height, 'height');
77
69
  this.__width__ = width;
78
70
  this.__height__ = height;
79
- this.__set_bitmap__(new Uint8ClampedArray(width * height * 4));
71
+ this.__set_bitmap__(allocate(width, height, () => new Uint8ClampedArray(width * height * 4)));
80
72
  }
81
73
  get gainMap() {
82
74
  return this.__gain_map__;
83
75
  }
84
76
  set gainMap(gainMap) {
85
77
  if (gainMap !== null && !(gainMap instanceof GainMap))
86
- throw new TypeError('The gain map has to be a GainMap or null');
78
+ throw new TypeError(`gainMap must be a GainMap or null, not ${shown(gainMap)}`);
87
79
  this.__gain_map__ = gainMap?.clone() ?? null;
88
80
  }
89
81
  get bitmap() {
90
82
  return this.__bitmap__;
91
83
  }
92
84
  set bitmap(bitmap) {
93
- if (!(bitmap instanceof Uint8ClampedArray || bitmap instanceof Uint8Array))
94
- throw new TypeError('The bitmap has to be a Uint8ClampedArray or Uint8Array');
85
+ instance(bitmap, [Uint8ClampedArray, Uint8Array], 'bitmap');
95
86
  if (bitmap.length !== this.width * this.height * 4)
96
- throw new RangeError(`The bitmap has to have ${this.width * this.height * 4} bytes (width * height * 4), got ${bitmap.length}`);
87
+ throw new RangeError(`bitmap must have ${this.width * this.height * 4} bytes (width * height * 4), not ${bitmap.length}`);
97
88
  if (bitmap.byteOffset % 4)
98
89
  throw new TypeError(`The bitmap has to start at a byte offset divisible by 4 to be used without copying, not ${bitmap.byteOffset} (pass bitmap.slice() for a copy)`);
99
90
  this.__set_bitmap__(bitmap instanceof Uint8ClampedArray ? bitmap : new Uint8ClampedArray(bitmap.buffer, bitmap.byteOffset, bitmap.length));
@@ -103,7 +94,7 @@ export class Image {
103
94
  bitmap = bitmap.slice();
104
95
  this.__bitmap__ = bitmap;
105
96
  this.__view__ = new DataView(bitmap.buffer, bitmap.byteOffset, bitmap.byteLength);
106
- this.__u32__ = new Uint32Array(bitmap.buffer, bitmap.byteOffset, bitmap.length >> 2);
97
+ this.__u32__ = new Uint32Array(bitmap.buffer, bitmap.byteOffset, bitmap.length >>> 2);
107
98
  }
108
99
  toString() {
109
100
  return `Image<${this.width}x${this.height}>`;
@@ -114,13 +105,15 @@ export class Image {
114
105
  get height() {
115
106
  return this.__height__;
116
107
  }
117
- *pixels() {
108
+ pixels() {
118
109
  const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength);
119
110
  const width = this.width, height = this.height;
120
- let offset = 0;
121
- for (let y = 0; y < height; y++)
122
- for (let x = 0; x < width; x++, offset += 4)
123
- yield [x, y, view.getUint32(offset, false)];
111
+ return (function* () {
112
+ let offset = 0;
113
+ for (let y = 0; y < height; y++)
114
+ for (let x = 0; x < width; x++, offset += 4)
115
+ yield [x, y, view.getUint32(offset, false)];
116
+ })();
124
117
  }
125
118
  static linearGradient(width, height, options) {
126
119
  checkOptions(options, 'Image.linearGradient(100, 50, { stops, angle: 90 })');
@@ -142,16 +135,16 @@ export class Image {
142
135
  }
143
136
  static radialGradient(width, height, options) {
144
137
  checkOptions(options, 'Image.radialGradient(100, 50, { stops })');
145
- const image = new Image(width, height);
146
- ({ width, height } = image);
138
+ width = pixels(width, 'width');
139
+ height = pixels(height, 'height');
147
140
  if (options === undefined || options.stops === undefined)
148
141
  throw new TypeError('Image.radialGradient(width, height, { stops }) needs the stops in the options');
149
142
  const { stops, x: cx = width / 2, y: cy = height / 2, radius = Math.hypot(Math.max(cx, width - cx), Math.max(cy, height - cy)) } = options;
150
143
  const color = gradientFunction(stops);
151
144
  finite(cx, 'x');
152
145
  finite(cy, 'y');
153
- if (!(finite(radius, 'radius') > 0))
154
- throw new RangeError('Invalid radius');
146
+ positive(radius, 'radius');
147
+ const image = new Image(width, height);
155
148
  const bitmap = new DataView(image.bitmap.buffer, image.bitmap.byteOffset, image.bitmap.byteLength);
156
149
  for (let y = 0, i = 0; y < height; y++)
157
150
  for (let x = 0; x < width; x++, i += 4)
@@ -175,21 +168,8 @@ export class Image {
175
168
  this.__view__.setUint32((y * this.width + x) * 4, pixelColor, false);
176
169
  }
177
170
  __check_boundaries__(x, y) {
178
- if (isNaN(x))
179
- throw new TypeError(`Invalid pixel coordinates (x=${x})`);
180
- if (isNaN(y))
181
- throw new TypeError(`Invalid pixel coordinates (y=${y})`);
182
- if (x < 0)
183
- throw new RangeError(`${Image.__out_of_bounds__} (x=${x})<0`);
184
- if (x >= this.width)
185
- throw new RangeError(`${Image.__out_of_bounds__} (x=${x})>=(width=${this.width})`);
186
- if (y < 0)
187
- throw new RangeError(`${Image.__out_of_bounds__} (y=${y})<0`);
188
- if (y >= this.height)
189
- throw new RangeError(`${Image.__out_of_bounds__} (y=${y})>=(height=${this.height})`);
190
- }
191
- static get __out_of_bounds__() {
192
- return 'Tried referencing a pixel outside of the images boundaries:';
171
+ coordinate(x, this.width - 1, 'x');
172
+ coordinate(y, this.height - 1, 'y');
193
173
  }
194
174
  fill(color) {
195
175
  const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength);
@@ -223,7 +203,7 @@ export class Image {
223
203
  scale(factor, options) {
224
204
  checkOptions(options, 'scale(factor, { mode: \'area\' })');
225
205
  const { mode } = resizeOptions(options);
226
- finite(factor, 'scale factor');
206
+ scaleFactor(factor, this.width, this.height);
227
207
  const image = this.__scale__(factor, mode);
228
208
  this.__gain_map__?.__rescale__(this.width, this.height, image.width, image.height);
229
209
  this.__moved__?.(image.width / this.width, image.height / this.height, 0, 0);
@@ -254,12 +234,8 @@ export class Image {
254
234
  const { background = 0x00000000, ...resizeOpts } = options ?? {};
255
235
  const backgroundColor = checkColor(background, 'background');
256
236
  resizeOptions(resizeOpts);
257
- width = Math.floor(finite(width, 'width'));
258
- height = Math.floor(finite(height, 'height'));
259
- if (width < 1)
260
- throw new RangeError('Image has to be at least 1 pixel wide');
261
- if (height < 1)
262
- throw new RangeError('Image has to be at least 1 pixel high');
237
+ width = pixels(width, 'width');
238
+ height = pixels(height, 'height');
263
239
  const result = new Image(width, height);
264
240
  if (backgroundColor !== 0)
265
241
  result.fill(backgroundColor);
@@ -272,12 +248,8 @@ export class Image {
272
248
  }
273
249
  __cover__(width, height, options) {
274
250
  const resizeOpts = resizeOptions(options);
275
- width = Math.floor(width);
276
- height = Math.floor(height);
277
- if (!(width >= 1 && Number.isFinite(width)))
278
- throw new RangeError('Image has to be at least 1 pixel wide');
279
- if (!(height >= 1 && Number.isFinite(height)))
280
- throw new RangeError('Image has to be at least 1 pixel high');
251
+ width = pixels(width, 'width');
252
+ height = pixels(height, 'height');
281
253
  const scale = Math.max(width / this.width, height / this.height);
282
254
  const resizedWidth = Math.max(width, Math.round(this.width * scale)), resizedHeight = Math.max(height, Math.round(this.height * scale));
283
255
  if (resizeOpts.mode !== 'nearest-neighbor' && width >= 1 && height >= 1) {
@@ -293,7 +265,7 @@ export class Image {
293
265
  }
294
266
  __resized_size__(width, height, fit = 'fill') {
295
267
  if (fit === 'inside' && width !== undefined && height !== undefined)
296
- return insideSize(this.width, this.height, width, height);
268
+ return insideSize(this.width, this.height, pixels(width, 'width'), pixels(height, 'height'));
297
269
  if (width === undefined)
298
270
  return [Math.max(1, Math.round(this.width / this.height * Math.floor(height))), height];
299
271
  if (height === undefined)
@@ -301,12 +273,8 @@ export class Image {
301
273
  return [width, height];
302
274
  }
303
275
  __resize__(width, height, mode = 'bilinear', region) {
304
- width = Math.floor(width);
305
- height = Math.floor(height);
306
- if (width < 1)
307
- throw new RangeError('Image has to be at least 1 pixel wide');
308
- if (height < 1)
309
- throw new RangeError('Image has to be at least 1 pixel high');
276
+ width = pixels(width, 'width');
277
+ height = pixels(height, 'height');
310
278
  oneOf(mode, RESIZE_MODES, 'resize mode');
311
279
  if (mode === 'nearest-neighbor')
312
280
  return this.__resize_nearest_neighbor__(width, height);
@@ -347,15 +315,7 @@ export class Image {
347
315
  return image;
348
316
  }
349
317
  __crop_bounds__(x, y, width, height) {
350
- x = Math.trunc(finite(x, 'x'));
351
- y = Math.trunc(finite(y, 'y'));
352
- width = Math.trunc(finite(width, 'width'));
353
- height = Math.trunc(finite(height, 'height'));
354
- const left = Math.max(0, x), top = Math.max(0, y);
355
- const right = Math.min(this.width, x + width), bottom = Math.min(this.height, y + height);
356
- if (right <= left || bottom <= top)
357
- throw new RangeError('Crop region does not overlap the image');
358
- return [left, top, right - left, bottom - top];
318
+ return cropBounds(this.width, this.height, x, y, width, height, 'image');
359
319
  }
360
320
  trim(options = {}) {
361
321
  checkOptions(options, 'trim({ tolerance: 0.1 })');
@@ -368,9 +328,7 @@ export class Image {
368
328
  return this.__apply__(this.__crop__(...bounds));
369
329
  }
370
330
  __trim_bounds__(color, { tolerance = 0 }) {
371
- finite(tolerance, 'tolerance');
372
- if (!(tolerance >= 0 && tolerance <= 1))
373
- throw new RangeError('Invalid tolerance, it has to be between 0 and 1');
331
+ unitInterval(tolerance, 'tolerance');
374
332
  const bitmap = this.bitmap;
375
333
  const { width, height } = this;
376
334
  if (color !== undefined)
@@ -471,36 +429,28 @@ export class Image {
471
429
  return this;
472
430
  }
473
431
  opacity(factor) {
474
- factor = finite(factor, 'opacity value');
475
- if (factor < 0)
476
- throw new RangeError('Invalid opacity value');
432
+ factor = nonNegative(factor, 'opacity factor');
477
433
  this.__set_channel_value__(factor, 3);
478
434
  return this;
479
435
  }
480
436
  red(factor) {
481
437
  if (this.__gain_map__)
482
438
  return this.__recolor__(image => image.red(factor));
483
- factor = finite(factor, 'red factor');
484
- if (factor < 0)
485
- throw new RangeError('Invalid red factor');
439
+ factor = nonNegative(factor, 'red factor');
486
440
  this.__set_channel_value__(factor, 0);
487
441
  return this;
488
442
  }
489
443
  green(factor) {
490
444
  if (this.__gain_map__)
491
445
  return this.__recolor__(image => image.green(factor));
492
- factor = finite(factor, 'green factor');
493
- if (factor < 0)
494
- throw new RangeError('Invalid green factor');
446
+ factor = nonNegative(factor, 'green factor');
495
447
  this.__set_channel_value__(factor, 1);
496
448
  return this;
497
449
  }
498
450
  blue(factor) {
499
451
  if (this.__gain_map__)
500
452
  return this.__recolor__(image => image.blue(factor));
501
- factor = finite(factor, 'blue factor');
502
- if (factor < 0)
503
- throw new RangeError('Invalid blue factor');
453
+ factor = nonNegative(factor, 'blue factor');
504
454
  this.__set_channel_value__(factor, 2);
505
455
  return this;
506
456
  }
@@ -511,17 +461,13 @@ export class Image {
511
461
  lightness(factor) {
512
462
  if (this.__gain_map__)
513
463
  return this.__recolor__(image => image.lightness(factor));
514
- factor = finite(factor, 'lightness factor');
515
- if (factor < 0)
516
- throw new RangeError('Invalid lightness factor');
464
+ factor = nonNegative(factor, 'lightness factor');
517
465
  return this.__map_hsla__(c => { c.l = factor * c.l; });
518
466
  }
519
467
  saturation(factor) {
520
468
  if (this.__gain_map__)
521
469
  return this.__recolor__(image => image.saturation(factor), true);
522
- factor = finite(factor, 'saturation factor');
523
- if (factor < 0)
524
- throw new RangeError('Invalid saturation factor');
470
+ factor = nonNegative(factor, 'saturation factor');
525
471
  return this.__map_hsla__(c => { c.s = factor * c.s; });
526
472
  }
527
473
  composite(source, options = {}) {
@@ -694,14 +640,14 @@ export class Image {
694
640
  __map_hsla__(map) {
695
641
  const bitmap = this.bitmap;
696
642
  const hsla = { h: 0, s: 0, l: 0, a: 0 };
697
- const pixels = new Uint32Array(bitmap.buffer, bitmap.byteOffset, bitmap.length >> 2);
643
+ const pixels = new Uint32Array(bitmap.buffer, bitmap.byteOffset, bitmap.length >>> 2);
698
644
  const keys = new Uint32Array(4096), values = new Uint32Array(4096);
699
645
  keys[0] = 1;
700
646
  for (let i = 0; i < bitmap.length; i += 4) {
701
- const color = pixels[i >> 2];
647
+ const color = pixels[i >>> 2];
702
648
  const slot = Math.imul(color, 0x9e3779b1) >>> 20;
703
649
  if (keys[slot] === color) {
704
- pixels[i >> 2] = values[slot];
650
+ pixels[i >>> 2] = values[slot];
705
651
  continue;
706
652
  }
707
653
  const r = bitmap[i] / 255, g = bitmap[i + 1] / 255, b = bitmap[i + 2] / 255;
@@ -739,7 +685,7 @@ export class Image {
739
685
  }
740
686
  bitmap[i + 3] = Math.round(na * 255);
741
687
  keys[slot] = color;
742
- values[slot] = pixels[i >> 2];
688
+ values[slot] = pixels[i >>> 2];
743
689
  }
744
690
  return this;
745
691
  }
@@ -763,14 +709,12 @@ export class Image {
763
709
  let fixed = null, count = 256;
764
710
  if (palette !== undefined) {
765
711
  if (!Array.isArray(palette))
766
- throw new TypeError('palette has to be an array of colors');
712
+ throw new TypeError(`palette must be an array of colors, not ${shown(palette)}`);
767
713
  if (palette.length < 1 || palette.length > 256)
768
- throw new RangeError(`palette needs 1 to 256 colors, not ${palette.length}`);
714
+ throw new RangeError(`palette must have 1-256 colors, not ${palette.length}`);
769
715
  const packed = new Uint8Array(palette.length * 3);
770
716
  palette.forEach((color, i) => {
771
717
  const value = checkColor(color, 'palette color');
772
- if (!Number.isInteger(value) || value < 0 || value > 0xffffffff)
773
- throw new RangeError(`Invalid palette color: ${color}`);
774
718
  packed[i * 3] = value >>> 24;
775
719
  packed[i * 3 + 1] = value >>> 16 & 255;
776
720
  packed[i * 3 + 2] = value >>> 8 & 255;
@@ -793,9 +737,9 @@ export class Image {
793
737
  }
794
738
  colorMatrix(matrix) {
795
739
  if (matrix === null || typeof matrix !== 'object')
796
- throw new TypeError(`colorMatrix() takes an array of 9 or 20 values, not ${matrix === null ? 'null' : typeof matrix}`);
740
+ throw new TypeError(`colorMatrix() takes an array of 9 or 20 values, not ${shown(matrix)}`);
797
741
  if (matrix.length !== 9 && matrix.length !== 20)
798
- throw new RangeError('A color matrix has 9 or 20 values');
742
+ throw new RangeError(`a color matrix must have 9 or 20 values, not ${matrix.length}`);
799
743
  const m = new Float64Array(20);
800
744
  const value = (v) => finite(v, 'color matrix value');
801
745
  if (matrix.length === 20)
@@ -822,13 +766,13 @@ export class Image {
822
766
  transform(matrix, options = {}) {
823
767
  checkOptions(options, 'image.transform([1, 0, 0, 1, 0, 0], { expand: false })');
824
768
  if (matrix === null || typeof matrix !== 'object')
825
- throw new TypeError(`transform() takes an array of 6 values, like transform([1, 0, 0, 1, 0, 0]), not ${matrix === null ? 'null' : typeof matrix}`);
769
+ throw new TypeError(`transform() takes an array of 6 values, like transform([1, 0, 0, 1, 0, 0]), not ${shown(matrix)}`);
826
770
  if (matrix.length !== 6)
827
- throw new RangeError('A transform has 6 values: [a, b, c, d, e, f]');
771
+ throw new RangeError(`a transform must have 6 values, [a, b, c, d, e, f], not ${matrix.length}`);
828
772
  const values = Array.from({ length: 6 }, (_, i) => finite(matrix[i], 'transform value'));
829
773
  const { origin = {}, expand = true, mode = 'bilinear' } = options;
830
774
  if (typeof origin !== 'object' || origin === null)
831
- throw new TypeError(`transform() takes an origin object like { x: 10, y: 20 }, not ${origin === null ? 'null' : typeof origin}`);
775
+ throw new TypeError(`transform() takes an origin object like { x: 10, y: 20 }, not ${shown(origin)}`);
832
776
  oneOf(mode, TRANSFORM_MODES, 'transform mode');
833
777
  boolean(expand, 'expand');
834
778
  const { x: pivotX = this.width / 2, y: pivotY = this.height / 2 } = origin;
@@ -851,8 +795,7 @@ export class Image {
851
795
  outHeight = Math.max(1, Math.round(maxY - minY));
852
796
  left = minX - (outWidth - (maxX - minX)) / 2;
853
797
  top = minY - (outHeight - (maxY - minY)) / 2;
854
- if (outWidth * outHeight > MAX_PIXELS)
855
- throw new RangeError(`The transformed image would have ${outWidth}x${outHeight} pixels, more than the ${MAX_PIXELS} allowed`);
798
+ checkGrowth(outWidth, outHeight, 'The transform');
856
799
  }
857
800
  const out = new Image(outWidth, outHeight);
858
801
  sampleAffine(this.bitmap, width, height, out.bitmap, outWidth, outHeight, inverse, left, top, mode);
@@ -870,10 +813,8 @@ export class Image {
870
813
  boolean(expand, 'expand');
871
814
  finite(x, 'x');
872
815
  finite(y, 'y');
873
- if (finite(blur, 'blur') < 0)
874
- throw new RangeError('Invalid blur radius');
875
- if (finite(spread, 'spread') < 0)
876
- throw new RangeError('Invalid spread');
816
+ nonNegative(blur, 'blur');
817
+ nonNegative(spread, 'spread');
877
818
  const [r, g, b, a] = Colors.toRGBA(checkColor(color));
878
819
  const reach = spread + 3 * blur, margin = Math.ceil(reach) + 1;
879
820
  const layer = this.__shape_layer__(margin);
@@ -910,8 +851,7 @@ export class Image {
910
851
  checkOptions(options, 'image.outline({ width: 4 })');
911
852
  const { width = 1, color = 0x000000ff, expand = true } = options;
912
853
  boolean(expand, 'expand');
913
- if (finite(width, 'outline width') < 0)
914
- throw new RangeError('Invalid outline width');
854
+ nonNegative(width, 'outline width');
915
855
  const [r, g, b, a] = Colors.toRGBA(checkColor(color));
916
856
  if (width === 0)
917
857
  return this;
@@ -980,25 +920,19 @@ export class Image {
980
920
  brightness(factor) {
981
921
  if (this.__gain_map__)
982
922
  return this.__recolor__(image => image.brightness(factor), false, v => v * factor);
983
- factor = finite(factor, 'brightness factor');
984
- if (factor < 0)
985
- throw new RangeError('Invalid brightness factor');
923
+ factor = nonNegative(factor, 'brightness factor');
986
924
  return this.__map_channels__(v => v * factor);
987
925
  }
988
926
  contrast(factor) {
989
927
  if (this.__gain_map__)
990
928
  return this.__recolor__(image => image.contrast(factor), false, v => (v - 0.5) * factor + 0.5);
991
- factor = finite(factor, 'contrast factor');
992
- if (factor < 0)
993
- throw new RangeError('Invalid contrast factor');
929
+ factor = nonNegative(factor, 'contrast factor');
994
930
  return this.__map_channels__(v => (v - 127.5) * factor + 127.5);
995
931
  }
996
932
  gamma(gamma) {
997
933
  if (this.__gain_map__)
998
934
  return this.__recolor__(image => image.gamma(gamma), false, v => Math.max(0, v) ** (1 / gamma));
999
- gamma = finite(gamma, 'gamma');
1000
- if (gamma <= 0)
1001
- throw new RangeError('Invalid gamma');
935
+ gamma = positive(gamma, 'gamma');
1002
936
  return this.__map_channels__(v => 255 * (v / 255) ** (1 / gamma));
1003
937
  }
1004
938
  grayscale() {
@@ -1028,7 +962,7 @@ export class Image {
1028
962
  finite(transparencyThreshold, 'transparencyThreshold');
1029
963
  finite(opacityThreshold, 'opacityThreshold');
1030
964
  if (!(transparencyThreshold >= 0 && opacityThreshold <= 1 && transparencyThreshold < opacityThreshold))
1031
- throw new RangeError('Invalid thresholds, they have to satisfy 0 <= transparencyThreshold < opacityThreshold <= 1');
965
+ throw new RangeError(`transparencyThreshold must be 0 or more and below opacityThreshold, which must be 1 or less, not ${transparencyThreshold} and ${opacityThreshold}`);
1032
966
  const bitmap = this.bitmap;
1033
967
  if (color !== undefined)
1034
968
  color = checkColor(color);
@@ -1082,7 +1016,7 @@ export class Image {
1082
1016
  boolean(ignoreWhite, 'ignoreWhite');
1083
1017
  const threshold = finite(bwThreshold, 'threshold');
1084
1018
  if (threshold < 0 || threshold > 256)
1085
- throw new RangeError(`threshold has to be between 0 and 256, not ${threshold}`);
1019
+ throw new RangeError(`threshold must be 0-256, not ${threshold}`);
1086
1020
  const pixels = this.__bytes__();
1087
1021
  const color = quantize.dominantColor(pixels, (r, g, b) => !(ignoreBlack && Math.max(r, g, b) < threshold) && !(ignoreWhite && Math.min(r, g, b) > 255 - threshold))
1088
1022
  || quantize.dominantColor(pixels, () => true);
@@ -1271,9 +1205,22 @@ export class Image {
1271
1205
  const backgroundColor = checkColor(background, 'background');
1272
1206
  const embed = gainMapEmbed(gainMapOption);
1273
1207
  const m = resolveMetadata(metadata);
1208
+ const exif = exifData(m), comment = m.comment ? utf8(m.comment) : undefined;
1209
+ if (comment && comment.length > 65533)
1210
+ throw new RangeError(`JPEG: the metadata's comment must be at most 65533 bytes in UTF-8, not ${comment.length}`);
1211
+ if (exif && exif.length > 65527)
1212
+ throw new RangeError(`JPEG: the metadata's description, author, copyright, software and creation time must be at most 65533 bytes together in Exif, not ${exif.length + 6}`);
1213
+ checkFormatSize('JPEG', this.width, this.height, 0xffff);
1214
+ if (!this.__gain_map__) {
1215
+ const flat = this.__flatRows__(backgroundColor);
1216
+ const base = { exif, comment, subsampling };
1217
+ if (!flat)
1218
+ return jpeg.encode(this.__bytes__(), this.width, this.height, quality, { ...base, gray: this.__is_gray__() });
1219
+ return jpeg.encode(flat.pixels, this.width, this.height, quality, { ...base, gray: flat.gray(), rows: flat.row });
1220
+ }
1274
1221
  const source = this.__flattened__(backgroundColor, embed !== null) ?? this;
1275
1222
  const gainMap = source.__gain_map__;
1276
- const base = { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined, subsampling, gray: source.__is_gray__() };
1223
+ const base = { exif, comment, subsampling, gray: source.__is_gray__() };
1277
1224
  if (!gainMap || !embed)
1278
1225
  return jpeg.encode(source.__bytes__(), source.width, source.height, quality, base);
1279
1226
  const { quality: mapQuality, scale } = embed;
@@ -1294,6 +1241,47 @@ export class Image {
1294
1241
  return false;
1295
1242
  return true;
1296
1243
  }
1244
+ __flatRows__(background) {
1245
+ const src = this.bitmap;
1246
+ let opaque = true;
1247
+ for (let i = 3; i < src.length && opaque; i += 4)
1248
+ opaque = src[i] === 255;
1249
+ if (opaque)
1250
+ return null;
1251
+ const width = this.width, bgR = background >>> 24, bgG = background >>> 16 & 255, bgB = background >>> 8 & 255;
1252
+ const scratch = new Uint8ClampedArray(width * 4);
1253
+ const row = (y) => {
1254
+ for (let x = 0, s = 4 * y * width, d = 0; x < width; x++, s += 4, d += 4) {
1255
+ const sa = src[s + 3];
1256
+ if (sa === 0) {
1257
+ scratch[d] = bgR;
1258
+ scratch[d + 1] = bgG;
1259
+ scratch[d + 2] = bgB;
1260
+ continue;
1261
+ }
1262
+ if (sa === 255) {
1263
+ scratch[d] = src[s];
1264
+ scratch[d + 1] = src[s + 1];
1265
+ scratch[d + 2] = src[s + 2];
1266
+ continue;
1267
+ }
1268
+ const fa = sa / 255, ba = 1 - fa, a = fa + ba;
1269
+ scratch[d] = (src[s] * fa + bgR * ba) / a;
1270
+ scratch[d + 1] = (src[s + 1] * fa + bgG * ba) / a;
1271
+ scratch[d + 2] = (src[s + 2] * fa + bgB * ba) / a;
1272
+ }
1273
+ };
1274
+ const gray = () => {
1275
+ for (let y = 0; y < this.height; y++) {
1276
+ row(y);
1277
+ for (let d = 0; d < scratch.length; d += 4)
1278
+ if (scratch[d] !== scratch[d + 1] || scratch[d] !== scratch[d + 2])
1279
+ return false;
1280
+ }
1281
+ return true;
1282
+ };
1283
+ return { pixels: new Uint8Array(scratch.buffer), row, gray };
1284
+ }
1297
1285
  __flattened__(background, withGainMap) {
1298
1286
  const pixels = this.bitmap;
1299
1287
  let opaque = true;
@@ -1314,6 +1302,7 @@ export class Image {
1314
1302
  checkThreads(threads);
1315
1303
  const exif = exifData(resolveMetadata(metadata));
1316
1304
  const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
1305
+ checkFormatSize('WebP', this.width, this.height, lossy ? 16383 : 16384);
1317
1306
  if (!lossy)
1318
1307
  return webp.encode(this.__bytes__(), this.width, this.height, exif, threads, effort);
1319
1308
  return webp.encodeLossy(this.__bytes__(), this.width, this.height, lossy, exif);
@@ -1328,8 +1317,7 @@ export class Image {
1328
1317
  checkOptions(options, 'image.encodeGIF({ colors: 64 })');
1329
1318
  const { colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85, metadata = {} } = options;
1330
1319
  const palette = quantize.paletteOptions(colors, dither, ditherStrength);
1331
- if (this.width > 0xffff || this.height > 0xffff)
1332
- throw new RangeError(`GIF: images can be at most 65535 pixels wide and high, not ${this.width}x${this.height}`);
1320
+ checkFormatSize('GIF', this.width, this.height, 0xffff);
1333
1321
  const frame = { x: 0, y: 0, width: this.width, height: this.height, delay: 0, dispose: 1, pixels: this.__bytes__() };
1334
1322
  return gif.encode({ width: this.width, height: this.height, loopCount: 0, frames: [frame] }, { colors: palette.colors, dither: palette.dither, strength: palette.strength }, gifComments(resolveMetadata(metadata)));
1335
1323
  }
@@ -1518,7 +1506,7 @@ export class Image {
1518
1506
  return this.__apply__(out);
1519
1507
  }
1520
1508
  static async renderSVG(svg, options = {}) {
1521
- checkOptions(options, 'renderSVG(svg, { width: 512 })');
1509
+ checkOptions(options, 'Image.renderSVG(svg, { width: 512 })');
1522
1510
  const { width: givenWidth, height: givenHeight, scale, maxPixels = MAX_PIXELS, font: fonts = [], images: givenImages = {} } = options;
1523
1511
  pixelLimit(maxPixels);
1524
1512
  const { maxLayerPixels = 4 * maxPixels, maxImagePixels = maxPixels } = options;
@@ -1529,16 +1517,16 @@ export class Image {
1529
1517
  throw new TypeError('renderSVG() takes one of width, height and scale');
1530
1518
  const mode = givenWidth !== undefined ? 'width' : givenHeight !== undefined ? 'height' : 'scale';
1531
1519
  const size = finite(mode === 'width' ? givenWidth : mode === 'height' ? givenHeight : scale === undefined ? 1 : scale, `SVG ${mode}`);
1532
- if (mode === 'scale' && size <= 0)
1533
- throw new RangeError('SVG scale must be > 0');
1534
- if (mode !== 'scale' && size < 1)
1535
- throw new RangeError(`SVG ${mode} must be >= 1`);
1520
+ if (mode === 'scale')
1521
+ positive(size, 'SVG scale');
1522
+ else
1523
+ atLeast(size, 1, `SVG ${mode}`);
1536
1524
  if (typeof givenImages !== 'object' || givenImages === null || Array.isArray(givenImages) || givenImages instanceof Map)
1537
1525
  throw new TypeError('SVG images must be an object of hrefs to image data');
1538
1526
  const given = new Map();
1539
1527
  for (const href of Object.keys(givenImages)) {
1540
1528
  const value = givenImages[href];
1541
- if (!(value instanceof Image) && !(value instanceof ArrayBuffer || ArrayBuffer.isView(value)))
1529
+ if (!(value instanceof Image) && !isBinaryData(value))
1542
1530
  throw new TypeError(`SVG image ${JSON.stringify(href)} must be BinaryData or an Image`);
1543
1531
  given.set(href, value);
1544
1532
  }
@@ -1576,16 +1564,18 @@ export class Image {
1576
1564
  images.set(href, { error: err instanceof LimitError ? tooLarge(err) : new Error(`SVG: the image ${shown(href)} can't be decoded`, { cause: err }) });
1577
1565
  }
1578
1566
  }
1579
- const { width, height, pixels } = svgRenderer.render(source, mode, size, images, (Array.isArray(fonts) ? fonts : [fonts]).map(font => view(font)), maxPixels, maxLayerPixels);
1567
+ const { width, height, pixels } = svgRenderer.render(source, mode, size, images, Array.from(Array.isArray(fonts) ? fonts : [fonts], font => view(font)), maxPixels, maxLayerPixels);
1580
1568
  const image = new Image(width, height);
1581
1569
  image.bitmap.set(pixels);
1582
1570
  return image;
1583
1571
  }
1584
1572
  static async renderText(text, options) {
1585
- if (typeof text !== 'string' || !isOptions(options))
1586
- throw new TypeError('renderText() takes the text and an options object, like renderText(\'Hello\', { font, size: 32 })');
1573
+ if (typeof text !== 'string')
1574
+ throw new TypeError(`Image.renderText() takes the text as a string, like Image.renderText('Hello', { font, size: 32 }), not ${shown(text)}`);
1575
+ if (!isOptions(options))
1576
+ throw new TypeError(`Image.renderText() takes an options object, like Image.renderText('Hello', { font, size: 32 }), not ${options === undefined ? 'undefined' : shown(options)}`);
1587
1577
  if (options.font === undefined)
1588
- throw new TypeError('renderText(text, options) needs the font in the options');
1578
+ throw new TypeError('Image.renderText(text, options) needs the font in the options');
1589
1579
  const { font, color = 0xffffffff, strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {}, maxPixels = MAX_PIXELS } = options;
1590
1580
  pixelLimit(maxPixels);
1591
1581
  boolean(hinting, 'hinting');
@@ -1593,12 +1583,12 @@ export class Image {
1593
1583
  const layout = textLayout({ width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign });
1594
1584
  const axes = textRenderer.axisValues(variations);
1595
1585
  const size = positive(options.size, 'font size');
1596
- if (finite(strokeWidth, 'stroke width') < 0)
1597
- throw new RangeError('Invalid stroke width');
1586
+ nonNegative(strokeWidth, 'stroke width');
1598
1587
  const fonts = Array.isArray(font) ? font : [font];
1599
1588
  if (!fonts.length)
1600
- throw new RangeError('No font given');
1589
+ throw new TypeError('font must be a font or an array of one or more fonts, not an empty array');
1601
1590
  const [r, g, b, a] = Colors.toRGBA(color);
1591
+ const [sr, sg, sb, sa] = Colors.toRGBA(strokeColor);
1602
1592
  const pad = Math.ceil(strokeWidth);
1603
1593
  if (layout.width !== undefined && layout.width <= 2 * pad)
1604
1594
  throw new RangeError(`The width (${layout.width}) leaves no room for the text inside the ${strokeWidth} pixel outline`);
@@ -1608,7 +1598,7 @@ export class Image {
1608
1598
  layout.width -= 2 * pad;
1609
1599
  if (layout.height !== undefined)
1610
1600
  layout.height -= 2 * pad;
1611
- const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features), axes, maxPixels, pad);
1601
+ const rendered = await textRenderer.render(Array.from(fonts, view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features), axes, maxPixels, pad);
1612
1602
  const width = rendered.width + 2 * pad, height = rendered.height + 2 * pad;
1613
1603
  const coverage = new Uint8Array(width * height);
1614
1604
  for (let y = 0; y < rendered.height; y++)
@@ -1622,7 +1612,7 @@ export class Image {
1622
1612
  const image = new Image(width, height);
1623
1613
  const bitmap = image.bitmap;
1624
1614
  if (!strokeWidth && !colored) {
1625
- const pixels = new Uint32Array(bitmap.buffer, bitmap.byteOffset, bitmap.length >> 2), lut = new Uint32Array(256);
1615
+ const pixels = new Uint32Array(bitmap.buffer, bitmap.byteOffset, bitmap.length >>> 2), lut = new Uint32Array(256);
1626
1616
  const bytes = new Uint8ClampedArray(lut.buffer);
1627
1617
  for (let v = 1; v < 256; v++)
1628
1618
  bytes.set([r, g, b, v * a / 255], v * 4);
@@ -1638,7 +1628,6 @@ export class Image {
1638
1628
  shape[i] = Math.max(shape[i], colored[i * 4 + 3]);
1639
1629
  }
1640
1630
  const stroke = strokeWidth ? outline(shape, width, height, strokeWidth) : null;
1641
- const [sr, sg, sb, sa] = Colors.toRGBA(strokeColor);
1642
1631
  for (let i = 0; i < coverage.length; i++) {
1643
1632
  let af = coverage[i] / 255 * a / 255, pr = r * af, pg = g * af, pb = b * af;
1644
1633
  if (colored && colored[i * 4 + 3]) {
@@ -1687,6 +1676,8 @@ export function alignedPixels(pixels) {
1687
1676
  }
1688
1677
  export function resizeArguments(widthOrOptions, height, options) {
1689
1678
  if (!isOptions(widthOrOptions)) {
1679
+ if (typeof widthOrOptions !== 'number')
1680
+ throw new TypeError(`resize() takes a width and a height, like resize(300, 200), or an options object, like resize({ width: 300 }), not ${shown(widthOrOptions)}`);
1690
1681
  checkOptions(options, 'resize(width, height, { mode: \'area\' })');
1691
1682
  return [finite(widthOrOptions, 'width'), finite(height, 'height'), options, 'fill'];
1692
1683
  }