imagescript 3.20.3 → 4.0.0-rc.2

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.
Files changed (55) hide show
  1. package/LICENSE +16 -12
  2. package/README.md +21 -12
  3. package/THIRD_PARTY_NOTICES.md +1 -1
  4. package/dist/animation-encoder.d.ts +1 -34
  5. package/dist/animation-encoder.js +35 -34
  6. package/dist/animation.d.ts +108 -122
  7. package/dist/animation.js +285 -121
  8. package/dist/codecs/av1/decode.js +1 -1
  9. package/dist/codecs/av1/encode.js +1 -1
  10. package/dist/codecs/gif.js +11 -9
  11. package/dist/codecs/hdr.d.ts +1 -1
  12. package/dist/codecs/jpeg.js +13 -13
  13. package/dist/codecs/jxl/headers.js +3 -3
  14. package/dist/codecs/jxl/patches-enc.js +1 -1
  15. package/dist/codecs/jxl.js +5 -5
  16. package/dist/codecs/netpbm.js +7 -7
  17. package/dist/codecs/png.js +15 -15
  18. package/dist/codecs/quantize.js +34 -8
  19. package/dist/codecs/tiff.js +1 -1
  20. package/dist/codecs/webp.js +3 -3
  21. package/dist/codecs/zlib.js +1 -1
  22. package/dist/colors.d.ts +8 -7
  23. package/dist/colors.js +23 -3
  24. package/dist/frame.d.ts +94 -100
  25. package/dist/frame.js +89 -65
  26. package/dist/gainmap.d.ts +88 -46
  27. package/dist/gainmap.js +75 -51
  28. package/dist/image-type.d.ts +6 -1
  29. package/dist/image-type.js +4 -1
  30. package/dist/image.d.ts +317 -738
  31. package/dist/image.js +308 -438
  32. package/dist/index.d.ts +19 -25
  33. package/dist/index.js +15 -14
  34. package/dist/metadata.d.ts +4 -3
  35. package/dist/metadata.js +9 -7
  36. package/dist/render/colr.js +1 -1
  37. package/dist/render/font.js +1 -1
  38. package/dist/render/layout.js +1 -1
  39. package/dist/render/segment.js +1 -1
  40. package/dist/render/shapers/hangul.js +1 -1
  41. package/dist/render/svg.js +68 -20
  42. package/dist/render/text.js +7 -9
  43. package/dist/text-layout.d.ts +5 -35
  44. package/dist/text-layout.js +11 -12
  45. package/dist/util/gain.js +12 -12
  46. package/dist/util/mem.d.ts +1 -1
  47. package/dist/util/optimize.js +3 -1
  48. package/dist/util/options.js +46 -7
  49. package/package.json +15 -10
  50. package/LICENSE.AGPL-3.0 +0 -619
  51. package/LICENSE.MIT +0 -19
  52. package/dist/gif.d.ts +0 -36
  53. package/dist/gif.js +0 -22
  54. package/dist/util/rotate.js +0 -43
  55. package/dist/version.js +0 -1
package/dist/image.js CHANGED
@@ -25,34 +25,18 @@ import { view } from "./util/mem.js";
25
25
  import { cicpTransform, colorSpaceTransform, profileTransform } from "./util/icc.js";
26
26
  import { ImageType } from "./image-type.js";
27
27
  import { TextLayout } from "./text-layout.js";
28
- import { resolveMetadata, pngText, exifData } from "./metadata.js";
28
+ import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
29
29
  import { encode as utf8 } from "./util/utf8.js";
30
30
  import { resample, BOX, TRIANGLE, CUBIC } from "./util/resample.js";
31
- import { rotateBilinear } from "./util/rotate.js";
32
31
  import { gaussianBlur, boxBlurRGBA, premultiply, unpremultiply } from "./util/blur.js";
33
- import { Colors, wrapHue, hue2rgb, rgbaToHSLA } from "./colors.js";
34
- import { isOptions, finite, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
35
- import { MAX_PIXELS, decoding } from "./util/limits.js";
32
+ import { Colors, wrapHue, hue2rgb } from "./colors.js";
33
+ import { isOptions, checkOptions, finite, oneOf, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
34
+ import { MAX_PIXELS, LimitError, decoding } from "./util/limits.js";
36
35
  import { GainMap } from "./gainmap.js";
37
36
  import * as gain from "./util/gain.js";
38
37
  import { multiply, invert } from "./util/matrix.js";
39
38
  import { sampleAffine } from "./util/affine.js";
40
39
  import * as gainMapCodec from "./codecs/gainmap.js";
41
- export class ResizeModes {
42
- static NEAREST_NEIGHBOR = 'nearest-neighbor';
43
- static BILINEAR = 'bilinear';
44
- static BICUBIC = 'bicubic';
45
- static AREA = 'area';
46
- static AUTO = -1;
47
- constructor() { }
48
- }
49
- export class SVGScaleModes {
50
- static SCALE = 'scale';
51
- static WIDTH = 'width';
52
- static HEIGHT = 'height';
53
- constructor() { }
54
- }
55
- const DITHER_METHODS = ['none', 'floyd-steinberg', 'atkinson', 'ordered'];
56
40
  const TRANSFORM_MODES = ['nearest-neighbor', 'bilinear', 'bicubic'];
57
41
  function featureList(features) {
58
42
  if (typeof features !== 'object' || features === null)
@@ -75,12 +59,16 @@ export class Image {
75
59
  __bitmap__;
76
60
  __gain_map__ = null;
77
61
  constructor(width, height) {
78
- width = ~~width;
79
- height = ~~height;
62
+ width = Math.trunc(finite(width, 'width'));
63
+ height = Math.trunc(finite(height, 'height'));
80
64
  if (width < 1)
81
65
  throw new RangeError('Image has to be at least 1 pixel wide');
82
66
  if (height < 1)
83
67
  throw new RangeError('Image has to be at least 1 pixel high');
68
+ if (width > 0x7fffffff)
69
+ throw new RangeError('Image width is too large');
70
+ if (height > 0x7fffffff)
71
+ throw new RangeError('Image height is too large');
84
72
  this.__width__ = width;
85
73
  this.__height__ = height;
86
74
  this.__set_bitmap__(new Uint8ClampedArray(width * height * 4));
@@ -101,6 +89,8 @@ export class Image {
101
89
  throw new TypeError('The bitmap has to be a Uint8ClampedArray or Uint8Array');
102
90
  if (bitmap.length !== this.width * this.height * 4)
103
91
  throw new RangeError(`The bitmap has to have ${this.width * this.height * 4} bytes (width * height * 4), got ${bitmap.length}`);
92
+ if (bitmap.byteOffset % 4)
93
+ 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)`);
104
94
  this.__set_bitmap__(bitmap instanceof Uint8ClampedArray ? bitmap : new Uint8ClampedArray(bitmap.buffer, bitmap.byteOffset, bitmap.length));
105
95
  }
106
96
  __set_bitmap__(bitmap) {
@@ -131,34 +121,8 @@ export class Image {
131
121
  for (let x = 0; x < this.width; x++, offset += 4)
132
122
  yield [x, y, view.getUint32(offset, false)];
133
123
  }
134
- *[Symbol.iterator]() {
135
- yield* this.coordinates();
136
- }
137
- *iterateWithColors() {
138
- yield* this.pixels();
139
- }
140
- static rgbaToColor(r, g, b, a) {
141
- return Colors.fromRGBA(r, g, b, a);
142
- }
143
- static rgbToColor(r, g, b) {
144
- return Colors.fromRGB(r, g, b);
145
- }
146
- static hslaToColor(h, s, l, a) {
147
- return Colors.fromHSLA(h, s, l, a);
148
- }
149
- static hslToColor(h, s, l) {
150
- return Colors.fromHSL(h, s, l);
151
- }
152
- static rgbaToHSLA(r, g, b, a) {
153
- return rgbaToHSLA(r, g, b, a);
154
- }
155
- static colorToRGBA(color) {
156
- return Colors.toRGBA(color);
157
- }
158
- static colorToRGB(color) {
159
- return Colors.toRGB(color);
160
- }
161
124
  static linearGradient(width, height, options) {
125
+ checkOptions(options, 'Image.linearGradient(100, 50, { stops, angle: 90 })');
162
126
  const { stops, angle = 180 } = options;
163
127
  const color = gradientFunction(stops);
164
128
  finite(angle, 'angle');
@@ -173,6 +137,7 @@ export class Image {
173
137
  return image;
174
138
  }
175
139
  static radialGradient(width, height, options) {
140
+ checkOptions(options, 'Image.radialGradient(100, 50, { stops })');
176
141
  const { stops, x: cx = width / 2, y: cy = height / 2, radius = Math.hypot(Math.max(cx, width - cx), Math.max(cy, height - cy)) } = options;
177
142
  const color = gradientFunction(stops);
178
143
  finite(cx, 'x');
@@ -186,27 +151,17 @@ export class Image {
186
151
  bitmap.setUint32(i, color(Math.hypot(x + 0.5 - cx, y + 0.5 - cy) / radius), false);
187
152
  return image;
188
153
  }
189
- static gradient(colors) {
190
- return Colors.gradient(colors);
191
- }
192
154
  getPixelAt(x, y) {
193
- x = ~~finite(x, 'x');
194
- y = ~~finite(y, 'y');
155
+ x = Math.trunc(finite(x, 'x'));
156
+ y = Math.trunc(finite(y, 'y'));
195
157
  this.__check_boundaries__(x, y);
196
158
  return this.__view__.getUint32((y * this.width + x) * 4, false);
197
159
  }
198
- getRGBAAt(x, y) {
199
- x = ~~finite(x, 'x');
200
- y = ~~finite(y, 'y');
160
+ setPixelAt(x, y, color) {
161
+ x = Math.trunc(finite(x, 'x'));
162
+ y = Math.trunc(finite(y, 'y'));
201
163
  this.__check_boundaries__(x, y);
202
- const idx = (y * this.width + x) * 4;
203
- return this.bitmap.subarray(idx, idx + 4);
204
- }
205
- setPixelAt(x, y, pixelColor) {
206
- x = ~~finite(x, 'x');
207
- y = ~~finite(y, 'y');
208
- this.__check_boundaries__(x, y);
209
- this.__set_pixel__(x, y, checkColor(pixelColor));
164
+ this.__set_pixel__(x, y, checkColor(color));
210
165
  return this;
211
166
  }
212
167
  __set_pixel__(x, y, pixelColor) {
@@ -233,21 +188,19 @@ export class Image {
233
188
  const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength);
234
189
  if (typeof color !== 'function')
235
190
  color = checkColor(color);
236
- if (this.__gain_map__)
237
- this.__gain_map__ = gain.neutralMap(this.__gain_map__, this.width, this.width, this.height);
238
191
  if (typeof color === 'function') {
239
192
  let offset = 0;
240
193
  for (let y = 0; y < this.height; y++)
241
194
  for (let x = 0; x < this.width; x++, offset += 4)
242
- view.setUint32(offset, color(x, y), false);
195
+ view.setUint32(offset, checkColor(color(x, y)), false);
243
196
  }
244
197
  else {
245
- if (!this.bitmap.length)
246
- return this;
247
198
  view.setUint32(0, color, false);
248
199
  const u32 = new Uint32Array(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength / 4);
249
200
  u32.fill(u32[0]);
250
201
  }
202
+ if (this.__gain_map__)
203
+ this.__gain_map__ = gain.neutralMap(this.__gain_map__, this.width, this.width, this.height);
251
204
  return this;
252
205
  }
253
206
  clone() {
@@ -258,47 +211,56 @@ export class Image {
258
211
  image.__gain_map__ = this.__gain_map__ ? this.__gain_map__.clone() : null;
259
212
  return image;
260
213
  }
261
- static RESIZE_NEAREST_NEIGHBOR = 'RESIZE_NEAREST_NEIGHBOR';
262
- static RESIZE_BILINEAR = 'RESIZE_BILINEAR';
263
- static RESIZE_BICUBIC = 'RESIZE_BICUBIC';
264
- static RESIZE_AREA = 'RESIZE_AREA';
265
- static RESIZE_AUTO = ResizeModes.AUTO;
266
- scale(factor, modeOrOptions) {
267
- const { mode, fast } = resizeOptions(modeOrOptions);
214
+ scale(factor, options) {
215
+ checkOptions(options, 'scale(factor, { mode: \'area\' })');
216
+ const { mode, fast } = resizeOptions(options);
268
217
  const image = this.__scale__(factor, mode, fast);
269
218
  this.__gain_map__?.__rescale__(this.width, this.height, image.width, image.height);
219
+ this.__moved__?.(image.width / this.width, image.height / this.height, 0, 0);
270
220
  return this.__apply__(image);
271
221
  }
272
- __scale__(factor, mode = ResizeModes.BILINEAR, fast = true) {
222
+ __scale__(factor, mode = 'bilinear', fast = true) {
273
223
  if (factor === 1)
274
224
  return this;
275
225
  return this.__resize__(this.width * factor, this.height * factor, mode, fast);
276
226
  }
277
- resize(widthOrOptions, heightArgument, modeArgument) {
278
- const [width, height, modeOrOptions] = resizeArguments(widthOrOptions, heightArgument, modeArgument);
279
- const { mode, fast } = resizeOptions(modeOrOptions);
280
- const image = this.__resize__(width, height, mode, fast);
227
+ resize(widthOrOptions, heightArgument, optionsArgument) {
228
+ const [width, height, options, fit] = resizeArguments(widthOrOptions, heightArgument, optionsArgument);
229
+ if (fit === 'contain' || fit === 'cover') {
230
+ if (width === undefined || height === undefined)
231
+ throw new TypeError(`resize({ fit: '${fit}' }) needs both width and height`);
232
+ return fit === 'contain'
233
+ ? this.__contain__(width, height, options)
234
+ : this.__cover__(width, height, options);
235
+ }
236
+ const { mode, fast } = resizeOptions(options);
237
+ const image = this.__resize__(...this.__resized_size__(width, height, fit), mode, fast);
281
238
  this.__gain_map__?.__rescale__(this.width, this.height, image.width, image.height);
239
+ this.__moved__?.(image.width / this.width, image.height / this.height, 0, 0);
282
240
  return this.__apply__(image);
283
241
  }
284
- contain(width, height, modeOrOptions) {
285
- const options = resizeOptions(modeOrOptions);
242
+ __contain__(width, height, options) {
243
+ const { background = 0x00000000, ...resizeOpts } = options ?? {};
244
+ const backgroundColor = checkColor(background, 'background');
245
+ resizeOptions(resizeOpts);
286
246
  width = Math.floor(finite(width, 'width'));
287
247
  height = Math.floor(finite(height, 'height'));
288
- const scale = Math.min(width / this.width, height / this.height);
289
- 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);
290
- }
291
- fit(width, height, modeOrOptions) {
292
- const options = resizeOptions(modeOrOptions);
248
+ if (width < 1)
249
+ throw new RangeError('Image has to be at least 1 pixel wide');
250
+ if (height < 1)
251
+ throw new RangeError('Image has to be at least 1 pixel high');
293
252
  const result = new Image(width, height);
294
- this.contain(width, height, options);
253
+ if (backgroundColor !== 0)
254
+ result.fill(backgroundColor);
255
+ this.resize(...insideSize(this.width, this.height, width, height), resizeOpts);
295
256
  const x = (width - this.width) / 2 | 0, y = (height - this.height) / 2 | 0;
296
- result.composite(this, x, y);
257
+ result.composite(this, { x, y });
297
258
  this.__gain_map__?.__transform__(this.width, this.height, result.width, result.height, (X, Y) => [X - x, Y - y]);
259
+ this.__moved__?.(1, 1, -x, -y);
298
260
  return this.__apply__(result);
299
261
  }
300
- cover(width, height, modeOrOptions) {
301
- const options = resizeOptions(modeOrOptions);
262
+ __cover__(width, height, options) {
263
+ const resizeOpts = resizeOptions(options);
302
264
  width = Math.floor(width);
303
265
  height = Math.floor(height);
304
266
  if (!(width >= 1 && Number.isFinite(width)))
@@ -307,34 +269,36 @@ export class Image {
307
269
  throw new RangeError('Image has to be at least 1 pixel high');
308
270
  const scale = Math.max(width / this.width, height / this.height);
309
271
  const resizedWidth = Math.max(width, Math.round(this.width * scale)), resizedHeight = Math.max(height, Math.round(this.height * scale));
310
- if (options.mode !== ResizeModes.NEAREST_NEIGHBOR && width >= 1 && height >= 1) {
272
+ if (resizeOpts.mode !== 'nearest-neighbor' && width >= 1 && height >= 1) {
311
273
  const region = { x: ~~((resizedWidth - width) / 2), y: ~~((resizedHeight - height) / 2), width, height };
312
- this.__rescaled__?.(resizedWidth, resizedHeight);
313
274
  const fx = resizedWidth / this.width, fy = resizedHeight / this.height;
314
275
  this.__gain_map__?.__transform__(this.width, this.height, width, height, (X, Y) => [(X + region.x) / fx, (Y + region.y) / fy], Math.min(fx, fy));
315
- return this.__apply__(this.__resize__(resizedWidth, resizedHeight, options.mode, options.fast, region));
276
+ this.__moved__?.(fx, fy, region.x, region.y);
277
+ return this.__apply__(this.__resize__(resizedWidth, resizedHeight, resizeOpts.mode, resizeOpts.fast, region));
316
278
  }
317
- this.resize(resizedWidth, resizedHeight, options);
279
+ this.resize(resizedWidth, resizedHeight, resizeOpts);
318
280
  return this.crop((this.width - width) / 2, (this.height - height) / 2, width, height);
319
281
  }
320
- __resize__(width, height, mode = ResizeModes.BILINEAR, fast = true, region) {
321
- if (width === ResizeModes.AUTO && height === ResizeModes.AUTO)
322
- throw new Error('RESIZE_AUTO can only be used for either width or height, not for both');
323
- else if (width === ResizeModes.AUTO)
324
- width = Math.max(1, Math.round(this.width / this.height * Math.floor(height)));
325
- else if (height === ResizeModes.AUTO)
326
- height = Math.max(1, Math.round(this.height / this.width * Math.floor(width)));
282
+ __resized_size__(width, height, fit = 'fill') {
283
+ if (fit === 'inside' && width !== undefined && height !== undefined)
284
+ return insideSize(this.width, this.height, width, height);
285
+ if (width === undefined)
286
+ return [Math.max(1, Math.round(this.width / this.height * Math.floor(height))), height];
287
+ if (height === undefined)
288
+ return [width, Math.max(1, Math.round(this.height / this.width * Math.floor(width)))];
289
+ return [width, height];
290
+ }
291
+ __resize__(width, height, mode = 'bilinear', fast = true, region) {
327
292
  width = Math.floor(width);
328
293
  height = Math.floor(height);
329
294
  if (width < 1)
330
295
  throw new RangeError('Image has to be at least 1 pixel wide');
331
296
  if (height < 1)
332
297
  throw new RangeError('Image has to be at least 1 pixel high');
333
- if (mode === ResizeModes.NEAREST_NEIGHBOR)
298
+ oneOf(mode, RESIZE_MODES, 'resize mode');
299
+ if (mode === 'nearest-neighbor')
334
300
  return this.__resize_nearest_neighbor__(width, height);
335
- const filter = mode === ResizeModes.BILINEAR ? TRIANGLE : mode === ResizeModes.BICUBIC ? CUBIC : mode === ResizeModes.AREA ? BOX : null;
336
- if (!filter)
337
- throw new Error('Invalid resize mode');
301
+ const filter = mode === 'bilinear' ? TRIANGLE : mode === 'bicubic' ? CUBIC : BOX;
338
302
  const image = new Image(region?.width ?? width, region?.height ?? height);
339
303
  resample(this.bitmap, this.width, this.height, width, height, filter, image.bitmap, fast, region);
340
304
  return image;
@@ -353,6 +317,7 @@ export class Image {
353
317
  crop(x, y, width, height) {
354
318
  const bounds = this.__crop_bounds__(x, y, width, height);
355
319
  this.__crop_gain_map__(this, ...bounds);
320
+ this.__moved__?.(1, 1, bounds[0], bounds[1]);
356
321
  return this.__apply__(this.__crop__(...bounds));
357
322
  }
358
323
  __crop_gain_map__(target, x, y, width, height) {
@@ -363,29 +328,31 @@ export class Image {
363
328
  copy.__transform__(this.width, this.height, width, height, (X, Y) => [X + x, Y + y]);
364
329
  target.__gain_map__ = copy;
365
330
  }
366
- region(x, y, width, height) {
331
+ extract(x, y, width, height) {
367
332
  const bounds = this.__crop_bounds__(x, y, width, height);
368
333
  const image = this.__crop__(...bounds);
369
334
  this.__crop_gain_map__(image, ...bounds);
370
335
  return image;
371
336
  }
372
337
  __crop_bounds__(x, y, width, height) {
373
- x = ~~finite(x, 'x');
374
- y = ~~finite(y, 'y');
375
- width = ~~finite(width, 'width');
376
- height = ~~finite(height, 'height');
338
+ x = Math.trunc(finite(x, 'x'));
339
+ y = Math.trunc(finite(y, 'y'));
340
+ width = Math.trunc(finite(width, 'width'));
341
+ height = Math.trunc(finite(height, 'height'));
377
342
  const left = Math.max(0, x), top = Math.max(0, y);
378
343
  const right = Math.min(this.width, x + width), bottom = Math.min(this.height, y + height);
379
344
  if (right <= left || bottom <= top)
380
345
  throw new RangeError('Crop region does not overlap the image');
381
346
  return [left, top, right - left, bottom - top];
382
347
  }
383
- trim(colorOrOptions, optionsArgument = {}) {
384
- const { color, ...options } = isOptions(colorOrOptions) ? colorOrOptions : { ...optionsArgument, color: colorOrOptions ?? optionsArgument.color };
385
- const bounds = this.__trim_bounds__(color, options);
348
+ trim(options = {}) {
349
+ checkOptions(options, 'trim({ tolerance: 0.1 })');
350
+ const { color, ...rest } = options;
351
+ const bounds = this.__trim_bounds__(color, rest);
386
352
  if (!bounds)
387
353
  return this;
388
354
  this.__crop_gain_map__(this, ...bounds);
355
+ this.__moved__?.(1, 1, bounds[0], bounds[1]);
389
356
  return this.__apply__(this.__crop__(...bounds));
390
357
  }
391
358
  __trim_bounds__(color, { tolerance = 0 }) {
@@ -441,84 +408,9 @@ export class Image {
441
408
  }
442
409
  return image;
443
410
  }
444
- drawBox(x, y, width, height, color) {
445
- x = ~~finite(x, 'x');
446
- y = ~~finite(y, 'y');
447
- width = ~~finite(width, 'width');
448
- height = ~~finite(height, 'height');
449
- if (typeof color !== 'function')
450
- this.__fast_box__(x, y, width, height, checkColor(color));
451
- else
452
- for (let tY = Math.max(0, -y); tY < height && tY + y < this.height; tY++)
453
- for (let tX = Math.max(0, -x); tX < width && tX + x < this.width; tX++)
454
- this.__set_pixel__(tX + x, tY + y, color(tX, tY));
455
- if (this.__gain_map__)
456
- gain.redraw(this, this.__gain_map__, Math.max(0, x), Math.max(0, y), Math.min(this.width, x + width), Math.min(this.height, y + height), (_x, _y, S, _boost, out) => {
457
- out[0] = S[0];
458
- out[1] = S[1];
459
- out[2] = S[2];
460
- });
461
- return this;
462
- }
463
- __fast_box__(x, y, width, height, color) {
464
- const left = Math.max(0, x), top = Math.max(0, y);
465
- const right = Math.min(this.width, x + width), bottom = Math.min(this.height, y + height);
466
- if (right <= left || bottom <= top)
467
- return this;
468
- for (let xPos = left; xPos < right; xPos++)
469
- this.__view__.setUint32(4 * (xPos + top * this.width), color);
470
- const start = 4 * (left + top * this.width);
471
- const end = 4 * (right + top * this.width);
472
- for (let row = top + 1; row < bottom; row++)
473
- this.bitmap.copyWithin(4 * (left + row * this.width), start, end);
474
- return this;
475
- }
476
- drawCircle(x, y, radius, color) {
477
- x = ~~finite(x, 'x');
478
- y = ~~finite(y, 'y');
479
- radius = finite(radius, 'radius');
480
- if (typeof color !== 'function')
481
- color = checkColor(color);
482
- const cx = x + 0.5, cy = y + 0.5;
483
- for (let py = Math.max(0, Math.floor(cy - radius)); py < Math.min(this.height, Math.ceil(cy + radius)); py++) {
484
- for (let px = Math.max(0, Math.floor(cx - radius)); px < Math.min(this.width, Math.ceil(cx + radius)); px++) {
485
- const coverage = circleCoverage(px, py, cx, cy, radius);
486
- if (coverage <= 0)
487
- continue;
488
- const value = typeof color === 'function' ? color(px - x + radius, py - y + radius) : color;
489
- if (coverage >= 1)
490
- this.__set_pixel__(px, py, value);
491
- else
492
- this.__blend_pixel__(px, py, value, coverage);
493
- }
494
- }
495
- const map = this.__gain_map__;
496
- if (map) {
497
- const oS = map.offsetSDR, oH = map.offsetHDR;
498
- gain.redraw(this, map, Math.max(0, Math.floor(cx - radius)), Math.max(0, Math.floor(cy - radius)), Math.min(this.width, Math.ceil(cx + radius)), Math.min(this.height, Math.ceil(cy + radius)), (px, py, S, boost, out) => {
499
- const coverage = Math.min(1, Math.max(0, circleCoverage(px, py, cx, cy, radius)));
500
- for (let c = 0; c < 3; c++)
501
- out[c] = coverage * S[c] + (1 - coverage) * ((S[c] + oS[c]) * boost[c] - oH[c]);
502
- });
503
- }
504
- return this;
505
- }
506
- __blend_pixel__(x, y, color, amount) {
507
- const i = (y * this.width + x) * 4, b = this.bitmap;
508
- const sa = (color & 0xff) / 255 * amount, da = b[i + 3] / 255 * (1 - amount);
509
- const a = sa + da;
510
- if (a <= 0) {
511
- b[i] = b[i + 1] = b[i + 2] = b[i + 3] = 0;
512
- return;
513
- }
514
- b[i] = ((color >>> 24) * sa + b[i] * da) / a;
515
- b[i + 1] = ((color >> 16 & 0xff) * sa + b[i + 1] * da) / a;
516
- b[i + 2] = ((color >> 8 & 0xff) * sa + b[i + 2] * da) / a;
517
- b[i + 3] = a * 255;
518
- }
519
- cropCircle(maxOrOptions = false, featheringArgument = 0) {
520
- const { max = false, size = max ? 'cover' : 'contain', feathering = 0 } = typeof maxOrOptions === 'object' && maxOrOptions !== null
521
- ? maxOrOptions : { max: maxOrOptions, feathering: featheringArgument };
411
+ cropCircle(options = {}) {
412
+ checkOptions(options, 'cropCircle({ size: \'cover\' })');
413
+ const { size = 'contain', feathering = 0 } = options;
522
414
  finite(feathering, 'feathering');
523
415
  if (size !== 'contain' && size !== 'cover')
524
416
  throw new TypeError(`Invalid circle size: ${String(size)}`);
@@ -566,77 +458,69 @@ export class Image {
566
458
  }
567
459
  return this;
568
460
  }
569
- opacity(opacity, absoluteOrOptions = false) {
570
- const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions;
461
+ opacity(opacity) {
571
462
  opacity = finite(opacity, 'opacity value');
572
463
  if (opacity < 0)
573
464
  throw new RangeError('Invalid opacity value');
574
- this.__set_channel_value__(opacity, absolute, 3);
465
+ this.__set_channel_value__(opacity, 3);
575
466
  return this;
576
467
  }
577
- red(factor, absoluteOrOptions = false) {
468
+ red(factor) {
578
469
  if (this.__gain_map__)
579
- return this.__recolor__(image => image.red(factor, absoluteOrOptions));
580
- const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions;
470
+ return this.__recolor__(image => image.red(factor));
581
471
  factor = finite(factor, 'red factor');
582
472
  if (factor < 0)
583
473
  throw new RangeError('Invalid red factor');
584
- this.__set_channel_value__(factor, absolute, 0);
474
+ this.__set_channel_value__(factor, 0);
585
475
  return this;
586
476
  }
587
- green(factor, absoluteOrOptions = false) {
477
+ green(factor) {
588
478
  if (this.__gain_map__)
589
- return this.__recolor__(image => image.green(factor, absoluteOrOptions));
590
- const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions;
479
+ return this.__recolor__(image => image.green(factor));
591
480
  factor = finite(factor, 'green factor');
592
481
  if (factor < 0)
593
482
  throw new RangeError('Invalid green factor');
594
- this.__set_channel_value__(factor, absolute, 1);
483
+ this.__set_channel_value__(factor, 1);
595
484
  return this;
596
485
  }
597
- blue(factor, absoluteOrOptions = false) {
486
+ blue(factor) {
598
487
  if (this.__gain_map__)
599
- return this.__recolor__(image => image.blue(factor, absoluteOrOptions));
600
- const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions;
488
+ return this.__recolor__(image => image.blue(factor));
601
489
  factor = finite(factor, 'blue factor');
602
490
  if (factor < 0)
603
491
  throw new RangeError('Invalid blue factor');
604
- this.__set_channel_value__(factor, absolute, 2);
492
+ this.__set_channel_value__(factor, 2);
605
493
  return this;
606
494
  }
607
- __set_channel_value__(value, absolute, offset) {
495
+ __set_channel_value__(value, offset) {
608
496
  for (let i = offset; i < this.bitmap.length; i += 4)
609
- this.bitmap[i] = value * (absolute ? 255 : this.bitmap[i]);
497
+ this.bitmap[i] = value * this.bitmap[i];
610
498
  }
611
- lightness(value, absoluteOrOptions = false) {
499
+ lightness(factor) {
612
500
  if (this.__gain_map__)
613
- return this.__recolor__(image => image.lightness(value, absoluteOrOptions));
614
- const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions;
615
- value = finite(value, 'lightness value');
616
- if (value < 0)
617
- throw new RangeError('Invalid lightness value');
618
- return this.__map_hsla__(c => { c.l = value * (absolute ? 1 : c.l); });
619
- }
620
- saturation(value, absoluteOrOptions = false) {
501
+ return this.__recolor__(image => image.lightness(factor));
502
+ factor = finite(factor, 'lightness factor');
503
+ if (factor < 0)
504
+ throw new RangeError('Invalid lightness factor');
505
+ return this.__map_hsla__(c => { c.l = factor * c.l; });
506
+ }
507
+ saturation(factor) {
621
508
  if (this.__gain_map__)
622
- return this.__recolor__(image => image.saturation(value, absoluteOrOptions), true);
623
- const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions;
624
- value = finite(value, 'saturation value');
625
- if (value < 0)
626
- throw new RangeError('Invalid saturation value');
627
- return this.__map_hsla__(c => { c.s = value * (absolute ? 1 : c.s); });
628
- }
629
- composite(source, xOrOptions = 0, yArgument = 0, optionsArgument = {}) {
630
- const options = isOptions(xOrOptions) ? xOrOptions : optionsArgument;
509
+ return this.__recolor__(image => image.saturation(factor), true);
510
+ factor = finite(factor, 'saturation factor');
511
+ if (factor < 0)
512
+ throw new RangeError('Invalid saturation factor');
513
+ return this.__map_hsla__(c => { c.s = factor * c.s; });
514
+ }
515
+ composite(source, options = {}) {
516
+ checkOptions(options, 'composite(source, { x: 10, y: 20 })');
631
517
  const { opacity = 1, mode = 'normal' } = options;
632
- let x = isOptions(xOrOptions) ? xOrOptions.x ?? 0 : xOrOptions, y = isOptions(xOrOptions) ? xOrOptions.y ?? 0 : yArgument;
633
- x = finite(x, 'x') | 0;
634
- y = finite(y, 'y') | 0;
518
+ let x = options.x ?? 0, y = options.y ?? 0;
519
+ x = Math.trunc(finite(x, 'x'));
520
+ y = Math.trunc(finite(y, 'y'));
635
521
  if (isNaN(opacity) || opacity < 0 || opacity > 1)
636
522
  throw new RangeError('Invalid composite opacity');
637
- const blend = BLEND_MODES[mode];
638
- if (!blend || !Object.prototype.hasOwnProperty.call(BLEND_MODES, mode))
639
- throw new RangeError(`Invalid blend mode: ${mode}`);
523
+ const blend = BLEND_MODES[oneOf(mode, Object.keys(BLEND_MODES), 'blend mode')];
640
524
  if (opacity === 0)
641
525
  return this;
642
526
  if (this.__gain_map__ || source.__gain_map__)
@@ -678,7 +562,7 @@ export class Image {
678
562
  const ownMap = this.__gain_map__, sourceMap = source.__gain_map__;
679
563
  this.__gain_map__ = source.__gain_map__ = null;
680
564
  try {
681
- this.composite(source, x, y, { opacity, mode });
565
+ this.composite(source, { x, y, opacity, mode });
682
566
  }
683
567
  finally {
684
568
  this.__gain_map__ = ownMap;
@@ -729,7 +613,7 @@ export class Image {
729
613
  }
730
614
  out[c] = share * Hs + (1 - share) * Hd;
731
615
  }
732
- }, map.channels === 1 && (!sourceMap || sourceMap.channels === 1), Math.max(0, ...(sourceMap?.gainMapMax ?? [0])));
616
+ }, map.channels === 1 && (!sourceMap || sourceMap.channels === 1), Math.max(0, ...(sourceMap?.__max__ ?? [0])));
733
617
  return this;
734
618
  }
735
619
  __blend__(source, x, y, opacity, blend) {
@@ -860,9 +744,10 @@ export class Image {
860
744
  return this;
861
745
  }
862
746
  quantize(options = {}) {
747
+ checkOptions(options, 'image.quantize({ colors: 16 })');
863
748
  if (typeof options !== 'object' || options === null)
864
749
  throw new TypeError('quantize takes an options object');
865
- const { colors, palette, dither = 'none', ditherStrength = 1 } = options;
750
+ const { colors, palette, dither = 'floyd-steinberg', ditherStrength = 0.85 } = options;
866
751
  if (colors !== undefined && palette !== undefined)
867
752
  throw new TypeError('quantize takes colors or palette, not both');
868
753
  let fixed = null, count = 256;
@@ -882,16 +767,10 @@ export class Image {
882
767
  });
883
768
  fixed = packed;
884
769
  }
885
- else if (colors !== undefined) {
886
- count = finite(colors, 'colors');
887
- if (!Number.isInteger(count) || count < 2 || count > 256)
888
- throw new RangeError(`colors must be an integer from 2 to 256, not ${colors}`);
889
- }
890
- if (!DITHER_METHODS.includes(dither))
891
- throw new TypeError(`dither must be one of ${DITHER_METHODS.map(name => `'${name}'`).join(', ')}, not ${String(dither)}`);
892
- const strength = finite(ditherStrength, 'ditherStrength');
893
- if (strength < 0 || strength > 1)
894
- throw new RangeError(`ditherStrength must be 0-1, not ${ditherStrength}`);
770
+ const checked = quantize.paletteOptions(palette === undefined ? colors : undefined, dither, ditherStrength);
771
+ if (checked.colors !== undefined)
772
+ count = checked.colors;
773
+ const strength = checked.strength;
895
774
  const reduce = (image) => {
896
775
  const bytes = image.__bytes__();
897
776
  const table = fixed ?? quantize.buildPalette(bytes, count, 1);
@@ -929,6 +808,7 @@ export class Image {
929
808
  return this;
930
809
  }
931
810
  transform(matrix, options = {}) {
811
+ checkOptions(options, 'image.transform([1, 0, 0, 1, 0, 0], { expand: false })');
932
812
  if (matrix === null || typeof matrix !== 'object' || matrix.length !== 6)
933
813
  throw new RangeError('A transform has 6 values: [a, b, c, d, e, f]');
934
814
  const values = Array.from({ length: 6 }, (_, i) => finite(typeof matrix[i] === 'number' ? matrix[i] : NaN, 'transform value'));
@@ -957,15 +837,6 @@ export class Image {
957
837
  outHeight = Math.max(1, Math.round(maxY - minY));
958
838
  left = minX - (outWidth - (maxX - minX)) / 2;
959
839
  top = minY - (outHeight - (maxY - minY)) / 2;
960
- const room = this.__room__();
961
- if (left < -room.left) {
962
- left = -room.left;
963
- outWidth = Math.max(1, Math.round(maxX - left));
964
- }
965
- if (top < -room.top) {
966
- top = -room.top;
967
- outHeight = Math.max(1, Math.round(maxY - top));
968
- }
969
840
  if (outWidth * outHeight > MAX_PIXELS)
970
841
  throw new RangeError(`The transformed image would have ${outWidth}x${outHeight} pixels, more than the ${MAX_PIXELS} allowed`);
971
842
  }
@@ -976,12 +847,11 @@ export class Image {
976
847
  const x = X + left, y = Y + top;
977
848
  return [inverse[0] * x + inverse[2] * y + inverse[4], inverse[1] * x + inverse[3] * y + inverse[5]];
978
849
  }, scale);
979
- this.__apply__(out);
980
- if (left || top)
981
- this.__grown__(-Math.round(left), -Math.round(top));
982
- return this;
850
+ this.__moved__?.(1, 1, left, top);
851
+ return this.__apply__(out);
983
852
  }
984
853
  dropShadow(options = {}) {
854
+ checkOptions(options, 'image.dropShadow({ blur: 8 })');
985
855
  const { x = 0, y = 0, blur = 0, spread = 0, color = 0x00000080, expand = true } = options;
986
856
  finite(x, 'x');
987
857
  finite(y, 'y');
@@ -1014,15 +884,15 @@ export class Image {
1014
884
  bitmap[i * 4 + 2] = b;
1015
885
  }
1016
886
  }
1017
- const room = this.__room__();
1018
887
  return this.__under__(layer, x - margin, y - margin, expand ? {
1019
- left: Math.min(room.left, Math.max(0, Math.ceil(reach - x))),
1020
- top: Math.min(room.top, Math.max(0, Math.ceil(reach - y))),
888
+ left: Math.max(0, Math.ceil(reach - x)),
889
+ top: Math.max(0, Math.ceil(reach - y)),
1021
890
  right: Math.max(0, Math.ceil(reach + x)),
1022
891
  bottom: Math.max(0, Math.ceil(reach + y))
1023
892
  } : { left: 0, top: 0, right: 0, bottom: 0 });
1024
893
  }
1025
894
  outline(options = {}) {
895
+ checkOptions(options, 'image.outline({ width: 4 })');
1026
896
  const { width = 1, color = 0x000000ff, expand = true } = options;
1027
897
  if (finite(width, 'outline width') < 0)
1028
898
  throw new RangeError('Invalid outline width');
@@ -1042,9 +912,9 @@ export class Image {
1042
912
  bitmap[i * 4 + 2] = b;
1043
913
  bitmap[i * 4 + 3] = stroke[i] * (1 - coverage[i] / 255) * a;
1044
914
  }
1045
- const room = this.__room__(), grow = Math.ceil(width);
915
+ const grow = Math.ceil(width);
1046
916
  return this.__under__(layer, -margin, -margin, expand
1047
- ? { left: Math.min(room.left, grow), top: Math.min(room.top, grow), right: grow, bottom: grow }
917
+ ? { left: grow, top: grow, right: grow, bottom: grow }
1048
918
  : { left: 0, top: 0, right: 0, bottom: 0 });
1049
919
  }
1050
920
  __shape_layer__(margin) {
@@ -1068,18 +938,12 @@ export class Image {
1068
938
  this.__gain_map__ = map;
1069
939
  }
1070
940
  map?.__transform__(this.width, this.height, width, height, (X, Y) => [X - left, Y - top]);
1071
- this.__apply__(result);
1072
- if (left || top)
1073
- this.__grown__(left, top);
1074
- return this;
1075
- }
1076
- __room__() {
1077
- return { left: Infinity, top: Infinity };
1078
- }
1079
- __grown__(_left, _top) {
941
+ this.__moved__?.(1, 1, -left, -top);
942
+ return this.__apply__(result);
1080
943
  }
1081
- sharpen(amountOrOptions = 1, radiusArgument = 1) {
1082
- const { amount = 1, radius = 1 } = isOptions(amountOrOptions) ? amountOrOptions : { amount: amountOrOptions, radius: radiusArgument };
944
+ sharpen(options = {}) {
945
+ checkOptions(options, 'sharpen({ amount: 0.5 })');
946
+ const { amount = 1, radius = 1 } = options;
1083
947
  if (!Number.isFinite(amount) || amount < 0)
1084
948
  throw new RangeError('Invalid sharpen amount');
1085
949
  if (!Number.isFinite(radius) || radius <= 0)
@@ -1122,9 +986,9 @@ export class Image {
1122
986
  throw new RangeError('Invalid gamma');
1123
987
  return this.__map_channels__(v => 255 * (v / 255) ** (1 / gamma));
1124
988
  }
1125
- greyscale() {
989
+ grayscale() {
1126
990
  if (this.__gain_map__)
1127
- return this.__recolor__(image => image.greyscale(), true);
991
+ return this.__recolor__(image => image.grayscale(), true);
1128
992
  const bitmap = this.bitmap;
1129
993
  for (let i = 0; i < bitmap.length; i += 4)
1130
994
  bitmap[i] = bitmap[i + 1] = bitmap[i + 2] = bitmap[i] * 19595 + bitmap[i + 1] * 38470 + bitmap[i + 2] * 7471 + 0x8000 >> 16;
@@ -1142,8 +1006,9 @@ export class Image {
1142
1006
  }
1143
1007
  return this;
1144
1008
  }
1145
- colorToAlpha(colorOrOptions, optionsArgument = {}) {
1146
- const { color: colorOption, transparencyThreshold = 0, opacityThreshold = 1 } = isOptions(colorOrOptions) ? colorOrOptions : { ...optionsArgument, color: colorOrOptions ?? optionsArgument.color };
1009
+ colorToAlpha(options = {}) {
1010
+ checkOptions(options, 'colorToAlpha({ color: 0xffffffff })');
1011
+ const { color: colorOption, transparencyThreshold = 0, opacityThreshold = 1 } = options;
1147
1012
  let color = colorOption;
1148
1013
  if (!(transparencyThreshold >= 0 && opacityThreshold <= 1 && transparencyThreshold < opacityThreshold))
1149
1014
  throw new RangeError('Invalid thresholds, they have to satisfy 0 <= transparencyThreshold < opacityThreshold <= 1');
@@ -1193,18 +1058,21 @@ export class Image {
1193
1058
  return Colors.fromRGBA(0, 0, 0, 0xff);
1194
1059
  return Colors.fromRGBA(Math.round(r / weight), Math.round(g / weight), Math.round(b / weight), 0xff);
1195
1060
  }
1196
- dominantColor(ignoreBlackOrOptions = true, ignoreWhiteArgument = true, thresholdArgument = 0xf) {
1197
- const { ignoreBlack = true, ignoreWhite = true, threshold: bwThreshold = 0xf } = typeof ignoreBlackOrOptions === 'object' && ignoreBlackOrOptions !== null
1198
- ? ignoreBlackOrOptions : { ignoreBlack: ignoreBlackOrOptions, ignoreWhite: ignoreWhiteArgument, threshold: thresholdArgument };
1061
+ dominantColor(options = {}) {
1062
+ checkOptions(options, 'dominantColor({ ignoreBlack: false })');
1063
+ const { ignoreBlack = true, ignoreWhite = true, threshold: bwThreshold = 0xf } = options;
1199
1064
  const threshold = Math.min(64, Math.max(0, finite(bwThreshold, 'threshold'))) * 4;
1200
1065
  const pixels = this.__bytes__();
1201
1066
  const color = quantize.dominantColor(pixels, (r, g, b) => !(ignoreBlack && Math.max(r, g, b) < threshold) && !(ignoreWhite && Math.min(r, g, b) > 255 - threshold))
1202
1067
  || quantize.dominantColor(pixels, () => true);
1203
1068
  return color ? Colors.fromRGB(...color) : Colors.fromRGBA(0, 0, 0, 0xff);
1204
1069
  }
1205
- rotate(angle, resizeOrOptions = true) {
1206
- const { resize = true, fast = true } = typeof resizeOrOptions === 'object' && resizeOrOptions !== null ? resizeOrOptions : { resize: resizeOrOptions };
1207
- angle = ((finite(angle, 'angle') % 360) + 360) % 360;
1070
+ rotate(angle, options = {}) {
1071
+ checkOptions(options, 'rotate(angle, { expand: false })');
1072
+ const { expand = true, mode = 'bilinear' } = options;
1073
+ if (!TRANSFORM_MODES.includes(mode))
1074
+ throw new TypeError(`rotate mode must be one of ${TRANSFORM_MODES.map(name => `'${name}'`).join(', ')}, not ${String(mode)}`);
1075
+ angle = ((-finite(angle, 'angle') % 360) + 360) % 360;
1208
1076
  if (angle === 0)
1209
1077
  return this;
1210
1078
  const { width, height } = this;
@@ -1230,86 +1098,36 @@ export class Image {
1230
1098
  dst[x * height + height - 1 - y] = i;
1231
1099
  }
1232
1100
  rotateGainMap(out.width, out.height);
1101
+ this.__moved__?.(1, 1, (width - out.width) / 2, (height - out.height) / 2);
1233
1102
  return this.__apply__(out);
1234
1103
  }
1235
1104
  const rad = angle * Math.PI / 180;
1236
1105
  const sin = Math.sin(rad), cos = Math.cos(rad);
1237
- const outWidth = resize ? Math.round(Math.abs(width * cos) + Math.abs(height * sin)) : width;
1238
- const outHeight = resize ? Math.round(Math.abs(width * sin) + Math.abs(height * cos)) : height;
1106
+ const outWidth = expand ? Math.round(Math.abs(width * cos) + Math.abs(height * sin)) : width;
1107
+ const outHeight = expand ? Math.round(Math.abs(width * sin) + Math.abs(height * cos)) : height;
1239
1108
  const out = new Image(outWidth, outHeight);
1240
1109
  rotateGainMap(outWidth, outHeight);
1241
- if (fast && rotateBilinear(this.bitmap, width, height, out.bitmap, outWidth, outHeight, sin, cos))
1242
- return this.__apply__(out);
1243
- const s8 = this.bitmap, d8 = out.bitmap;
1244
- for (let oy = 0; oy < outHeight; oy++) {
1245
- for (let ox = 0; ox < outWidth; ox++) {
1246
- const dx = ox + 0.5 - outWidth / 2, dy = oy + 0.5 - outHeight / 2;
1247
- const sx = dx * cos - dy * sin + width / 2 - 0.5;
1248
- const sy = dx * sin + dy * cos + height / 2 - 0.5;
1249
- const x0 = Math.floor(sx), y0 = Math.floor(sy);
1250
- if (x0 < -1 || y0 < -1 || x0 >= width || y0 >= height)
1251
- continue;
1252
- const fx = sx - x0, fy = sy - y0;
1253
- const w00 = (1 - fx) * (1 - fy), w10 = fx * (1 - fy), w01 = (1 - fx) * fy, w11 = fx * fy;
1254
- let r = 0, g = 0, b = 0, a = 0;
1255
- const left = x0 >= 0, right = x0 + 1 < width, top = y0 >= 0, bottom = y0 + 1 < height;
1256
- let i = 4 * (y0 * width + x0);
1257
- if (top && left) {
1258
- const wa = w00 * s8[i + 3];
1259
- r += wa * s8[i];
1260
- g += wa * s8[i + 1];
1261
- b += wa * s8[i + 2];
1262
- a += wa;
1263
- }
1264
- if (top && right) {
1265
- const wa = w10 * s8[i + 7];
1266
- r += wa * s8[i + 4];
1267
- g += wa * s8[i + 5];
1268
- b += wa * s8[i + 6];
1269
- a += wa;
1270
- }
1271
- i += 4 * width;
1272
- if (bottom && left) {
1273
- const wa = w01 * s8[i + 3];
1274
- r += wa * s8[i];
1275
- g += wa * s8[i + 1];
1276
- b += wa * s8[i + 2];
1277
- a += wa;
1278
- }
1279
- if (bottom && right) {
1280
- const wa = w11 * s8[i + 7];
1281
- r += wa * s8[i + 4];
1282
- g += wa * s8[i + 5];
1283
- b += wa * s8[i + 6];
1284
- a += wa;
1285
- }
1286
- if (a <= 0)
1287
- continue;
1288
- const o = 4 * (oy * outWidth + ox);
1289
- d8[o] = r / a;
1290
- d8[o + 1] = g / a;
1291
- d8[o + 2] = b / a;
1292
- d8[o + 3] = a;
1293
- }
1294
- }
1110
+ const inverse = [cos, sin, -sin, cos,
1111
+ width / 2 - cos * outWidth / 2 + sin * outHeight / 2, height / 2 - sin * outWidth / 2 - cos * outHeight / 2];
1112
+ sampleAffine(this.bitmap, width, height, out.bitmap, outWidth, outHeight, inverse, 0, 0, mode);
1113
+ this.__moved__?.(1, 1, (width - outWidth) / 2, (height - outHeight) / 2);
1295
1114
  return this.__apply__(out);
1296
1115
  }
1297
1116
  flip(direction) {
1117
+ oneOf(direction, ['horizontal', 'vertical'], 'flip direction');
1298
1118
  const u32 = this.__u32__;
1299
1119
  const { width, height } = this;
1300
1120
  if (direction === 'horizontal') {
1301
1121
  for (let y = 0; y < height; y++)
1302
1122
  u32.subarray(y * width, (y + 1) * width).reverse();
1303
1123
  }
1304
- else if (direction === 'vertical') {
1124
+ else {
1305
1125
  for (let y = 0; y < height >> 1; y++) {
1306
1126
  const top = u32.slice(y * width, (y + 1) * width);
1307
1127
  u32.copyWithin(y * width, (height - 1 - y) * width, (height - y) * width);
1308
1128
  u32.set(top, (height - 1 - y) * width);
1309
1129
  }
1310
1130
  }
1311
- else
1312
- throw new RangeError('Invalid flip direction');
1313
1131
  this.__gain_map__?.__transform__(width, height, width, height, direction === 'horizontal' ? (X, Y) => [width - X, Y] : (X, Y) => [X, height - Y]);
1314
1132
  return this;
1315
1133
  }
@@ -1352,8 +1170,9 @@ export class Image {
1352
1170
  this.__u32__ = image.__u32__;
1353
1171
  return this;
1354
1172
  }
1355
- roundCorners(radiusOrOptions) {
1356
- let radius = (isOptions(radiusOrOptions) ? radiusOrOptions.radius : radiusOrOptions) ?? Math.min(this.width, this.height) / 4;
1173
+ roundCorners(options = {}) {
1174
+ checkOptions(options, 'roundCorners({ radius: 10 })');
1175
+ let radius = options.radius ?? Math.min(this.width, this.height) / 4;
1357
1176
  radius = finite(radius, 'radius');
1358
1177
  radius = Math.max(0, Math.min(radius, this.width / 2, this.height / 2));
1359
1178
  const size = Math.ceil(radius);
@@ -1369,8 +1188,9 @@ export class Image {
1369
1188
  }
1370
1189
  return this;
1371
1190
  }
1372
- fisheye(strengthOrOptions) {
1373
- const strength = finite((isOptions(strengthOrOptions) ? strengthOrOptions.strength : strengthOrOptions) ?? 2, 'strength');
1191
+ fisheye(options = {}) {
1192
+ checkOptions(options, 'fisheye({ strength: 3 })');
1193
+ const strength = finite(options.strength ?? 2, 'strength');
1374
1194
  const r = new Image(this.width, this.height);
1375
1195
  const w = this.width;
1376
1196
  const h = this.height;
@@ -1402,26 +1222,23 @@ export class Image {
1402
1222
  });
1403
1223
  return this.__apply__(r);
1404
1224
  }
1405
- async encodePNG(compressionOrOptions = 4, metadataArgument = {}) {
1406
- let compression = 4, metadata = metadataArgument;
1407
- if (!isOptions(compressionOrOptions))
1408
- compression = compressionOrOptions;
1409
- else if ('compression' in compressionOrOptions || 'metadata' in compressionOrOptions)
1410
- ({ compression = 4, metadata = {} } = compressionOrOptions);
1411
- else
1412
- metadata = compressionOrOptions;
1225
+ async encodePNG(options = {}) {
1226
+ checkOptions(options, 'encodePNG({ compression: 9, metadata: { author: \'me\' } })');
1227
+ const { compression = 4, metadata = {} } = options;
1413
1228
  return png.encodeRGBA(this.__bytes__(), this.width, this.height, compressionLevel(compression), pngText(resolveMetadata(metadata)));
1414
1229
  }
1415
- encode(compressionOrOptions, metadata) {
1416
- return this.encodePNG(compressionOrOptions, metadata);
1417
- }
1418
- async encodeJPEG(qualityOrOptions = 90) {
1419
- const { quality = 90, metadata = {}, gainMap: gainMapOption = true } = isOptions(qualityOrOptions) ? qualityOrOptions : { quality: qualityOrOptions };
1230
+ async encodeJPEG(options = {}) {
1231
+ checkOptions(options, 'encodeJPEG({ quality: 80 })');
1232
+ const { quality = 90, subsampling, background = 0x000000ff, metadata = {}, gainMap: gainMapOption = true } = options;
1233
+ if (subsampling !== undefined && subsampling !== '4:4:4' && subsampling !== '4:2:0')
1234
+ throw new TypeError(`subsampling must be '4:4:4' or '4:2:0', not ${String(subsampling)}`);
1235
+ const backgroundColor = checkColor(background, 'background');
1420
1236
  const m = resolveMetadata(metadata);
1421
- const base = { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined };
1422
- const gainMap = this.__gain_map__;
1237
+ const base = { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined, subsampling };
1238
+ const source = this.__flattened__(backgroundColor, gainMapOption !== false) ?? this;
1239
+ const gainMap = source.__gain_map__;
1423
1240
  if (!gainMap || gainMapOption === false)
1424
- return jpeg.encode(this.__bytes__(), this.width, this.height, finite(quality, 'quality'), base);
1241
+ return jpeg.encode(source.__bytes__(), source.width, source.height, finite(quality, 'quality'), base);
1425
1242
  const { quality: mapQuality, scale } = typeof gainMapOption === 'object' && gainMapOption !== null ? gainMapOption : {};
1426
1243
  let width, height;
1427
1244
  if (scale !== undefined) {
@@ -1433,10 +1250,26 @@ export class Image {
1433
1250
  }
1434
1251
  const params = gainMap.__params__();
1435
1252
  const map = gainMapCodec.mapWithMetadata(gainMap.__body__(mapQuality === undefined ? undefined : Math.max(1, checkQuality(mapQuality, 'gain map quality')), width, height), params);
1436
- const primary = jpeg.encode(this.__bytes__(), this.width, this.height, finite(quality, 'quality'), { ...base, segments: gainMapCodec.primarySegments(map.length) });
1253
+ const primary = jpeg.encode(source.__bytes__(), source.width, source.height, finite(quality, 'quality'), { ...base, segments: gainMapCodec.primarySegments(map.length) });
1437
1254
  return gainMapCodec.finish(primary, map);
1438
1255
  }
1439
- async encodeWebP({ quality, effort = 2, sharpYuv = false, alphaQuality = 100, threads = defaultThreads(), metadata = {} } = {}) {
1256
+ __flattened__(background, withGainMap) {
1257
+ const pixels = this.bitmap;
1258
+ let opaque = true;
1259
+ for (let i = 3; i < pixels.length && opaque; i += 4)
1260
+ opaque = pixels[i] === 255;
1261
+ if (opaque)
1262
+ return null;
1263
+ const flat = new Image(this.width, this.height).fill((background | 0xff) >>> 0);
1264
+ if (withGainMap || !this.__gain_map__)
1265
+ return flat.composite(this);
1266
+ const withoutMap = this.clone();
1267
+ withoutMap.gainMap = null;
1268
+ return flat.composite(withoutMap);
1269
+ }
1270
+ async encodeWebP(options = {}) {
1271
+ checkOptions(options, 'image.encodeWebP({ quality: 80 })');
1272
+ const { quality, effort = 2, sharpYuv = false, alphaQuality = 100, threads = defaultThreads(), metadata = {} } = options;
1440
1273
  checkThreads(threads);
1441
1274
  const exif = exifData(resolveMetadata(metadata));
1442
1275
  const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
@@ -1444,17 +1277,30 @@ export class Image {
1444
1277
  return webp.encode(this.__bytes__(), this.width, this.height, exif, threads, effort);
1445
1278
  return webp.encodeLossy(this.__bytes__(), this.width, this.height, lossy, exif);
1446
1279
  }
1447
- async encodeTGA({ metadata = {} } = {}) {
1280
+ async encodeTGA(options = {}) {
1281
+ checkOptions(options, 'image.encodeTGA({ metadata })');
1282
+ const { metadata = {} } = options;
1448
1283
  const { author, comment, creationTime: time, software } = resolveMetadata(metadata);
1449
1284
  return tga.encode(this.__bytes__(), this.width, this.height, { author, comment, time, software });
1450
1285
  }
1286
+ async encodeGIF(options = {}) {
1287
+ checkOptions(options, 'image.encodeGIF({ colors: 64 })');
1288
+ const { colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85, metadata = {} } = options;
1289
+ const palette = quantize.paletteOptions(colors, dither, ditherStrength);
1290
+ if (this.width > 0xffff || this.height > 0xffff)
1291
+ throw new RangeError(`GIF: images can be at most 65535 pixels wide and high, not ${this.width}x${this.height}`);
1292
+ const frame = { x: 0, y: 0, width: this.width, height: this.height, delay: 0, dispose: 1, pixels: this.__bytes__() };
1293
+ 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)));
1294
+ }
1451
1295
  async encodeBMP() {
1452
1296
  return bmp.encode(this.__bytes__(), this.width, this.height);
1453
1297
  }
1454
1298
  async encodeQOI() {
1455
1299
  return qoi.encode(this.__bytes__(), this.width, this.height);
1456
1300
  }
1457
- async encodeAVIF({ quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true } = {}) {
1301
+ async encodeAVIF(options = {}) {
1302
+ checkOptions(options, 'image.encodeAVIF({ quality: 60 })');
1303
+ const { quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true } = options;
1458
1304
  checkEffort(effort, 2);
1459
1305
  checkThreads(threads);
1460
1306
  if (subsampling !== '4:4:4' && subsampling !== '4:2:0')
@@ -1481,7 +1327,9 @@ export class Image {
1481
1327
  }
1482
1328
  return { pixels: map.__bytes__(), width: map.width, height: map.height, params: gainMap.__params__(), quality: mapQuality };
1483
1329
  }
1484
- async encodeJXL({ quality, effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true } = {}) {
1330
+ async encodeJXL(options = {}) {
1331
+ checkOptions(options, 'image.encodeJXL({ quality: 90 })');
1332
+ const { quality, effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true } = options;
1485
1333
  checkEffort(effort, 2);
1486
1334
  checkThreads(threads);
1487
1335
  const distanceOf = (q) => q >= 100 ? 0 : q >= 30 ? 0.1 + (100 - q) * 0.09 : 53 / 3000 * q * q - 23 / 20 * q + 25;
@@ -1493,6 +1341,7 @@ export class Image {
1493
1341
  return netpbm.encode(this.__bytes__(), this.width, this.height);
1494
1342
  }
1495
1343
  static async decode(input, options = {}) {
1344
+ checkOptions(options, 'Image.decode(data, { maxPixels: 1e8 })');
1496
1345
  const { applyOrientation = true, applyColorProfile = true, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = defaultThreads(), gainMap = true } = options;
1497
1346
  checkThreads(threads);
1498
1347
  if (!(Number(maxPixels) > 0))
@@ -1509,9 +1358,10 @@ export class Image {
1509
1358
  if (ImageType.isTIFF(dataView))
1510
1359
  return tiff.decode(data, maxPixels);
1511
1360
  if (ImageType.isWebP(dataView)) {
1512
- if (webp.isAnimated(data))
1513
- throw new Error('Animated WebPs have to be decoded with Animation.decode()');
1514
- return webp.decode(data, maxPixels);
1361
+ if (!webp.isAnimated(data))
1362
+ return webp.decode(data, maxPixels);
1363
+ const animation = webp.decodeAnimation(data, true, maxPixels);
1364
+ return { width: animation.width, height: animation.height, pixels: webp.composite(animation)[0].pixels, orientation: animation.orientation, icc: animation.icc };
1515
1365
  }
1516
1366
  const bitmap = async (decoded) => {
1517
1367
  if (!('embedded' in decoded))
@@ -1525,7 +1375,7 @@ export class Image {
1525
1375
  return jxl.decode(data, maxPixels, toneMapping, threads, gainMap);
1526
1376
  if (ImageType.isBMP(dataView))
1527
1377
  return bitmap(bmp.decode(data, maxPixels));
1528
- if (ImageType.isICO(dataView))
1378
+ if (ImageType.isICO(dataView) || ImageType.isCUR(dataView))
1529
1379
  return bitmap(ico.decode(data, maxPixels));
1530
1380
  if (ImageType.isQOI(dataView))
1531
1381
  return qoi.decode(data, maxPixels);
@@ -1535,8 +1385,13 @@ export class Image {
1535
1385
  return hdr.decode(data, maxPixels, toneMapping);
1536
1386
  if (ImageType.isTGA(dataView))
1537
1387
  return tga.decode(data, maxPixels);
1538
- if (ImageType.isGIF(dataView))
1539
- throw new Error('GIFs have to be decoded with Animation.decode() (or decode(), which returns an image or an animation)');
1388
+ if (ImageType.isGIF(dataView)) {
1389
+ const gifData = gif.decode(data, true, maxPixels);
1390
+ const [first] = gif.composite(gifData);
1391
+ if (!first)
1392
+ throw new Error('GIF: no frames');
1393
+ return { width: gifData.width, height: gifData.height, pixels: first.pixels };
1394
+ }
1540
1395
  throw new Error('Unsupported image type');
1541
1396
  });
1542
1397
  if (applyColorProfile) {
@@ -1544,7 +1399,7 @@ export class Image {
1544
1399
  (icc ? profileTransform(icc) : cicp ? cicpTransform(...cicp) : colorSpace ? colorSpaceTransform(colorSpace.xy, colorSpace.curve) : null)?.(decoded.pixels);
1545
1400
  }
1546
1401
  const image = new Image(decoded.width, decoded.height);
1547
- image.bitmap = decoded.pixels;
1402
+ image.bitmap = alignedPixels(decoded.pixels);
1548
1403
  if (gainMap && ImageType.isJPEG(dataView)) {
1549
1404
  try {
1550
1405
  const found = gainMapCodec.find(data);
@@ -1559,7 +1414,7 @@ export class Image {
1559
1414
  if (decoded.gainMap) {
1560
1415
  const { width, height, pixels, params } = decoded.gainMap;
1561
1416
  const map = new Image(width, height);
1562
- map.bitmap = pixels;
1417
+ map.bitmap = alignedPixels(pixels);
1563
1418
  image.__gain_map__ = GainMap.__from_pixels__(map, params);
1564
1419
  }
1565
1420
  if (applyOrientation && decoded.orientation && decoded.orientation > 1) {
@@ -1622,19 +1477,25 @@ export class Image {
1622
1477
  }
1623
1478
  return this.__apply__(out);
1624
1479
  }
1625
- static SVG_MODE_SCALE = 1;
1626
- static SVG_MODE_WIDTH = 2;
1627
- static SVG_MODE_HEIGHT = 3;
1628
- static async renderSVG(svg, sizeOrOptions = 1, modeArgument = SVGScaleModes.SCALE) {
1629
- const { size = 1, mode: givenMode = SVGScaleModes.SCALE, fonts = [], images: givenImages = {} } = isOptions(sizeOrOptions) ? sizeOrOptions : { size: sizeOrOptions, mode: modeArgument };
1630
- const mode = LEGACY_SVG_MODES.get(givenMode) ?? givenMode;
1631
- if (mode !== 'scale' && mode !== 'width' && mode !== 'height')
1632
- throw new Error('Invalid SVG scaling mode');
1633
- finite(size, 'SVG size');
1634
- if (mode === SVGScaleModes.SCALE && size <= 0)
1480
+ static async renderSVG(svg, options = {}) {
1481
+ checkOptions(options, 'renderSVG(svg, { width: 512 })');
1482
+ const { width: givenWidth, height: givenHeight, scale, maxPixels = MAX_PIXELS, fonts = [], images: givenImages = {} } = options;
1483
+ if (!(Number(maxPixels) > 0))
1484
+ throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
1485
+ const { maxLayerPixels = 4 * Number(maxPixels), maxImagePixels = Number(maxPixels) } = options;
1486
+ if (!(Number(maxLayerPixels) > 0))
1487
+ throw new RangeError(`maxLayerPixels must be a positive number, not ${maxLayerPixels}`);
1488
+ if (!(Number(maxImagePixels) > 0))
1489
+ throw new RangeError(`maxImagePixels must be a positive number, not ${maxImagePixels}`);
1490
+ const sizes = [givenWidth, givenHeight, scale].filter(value => value !== undefined).length;
1491
+ if (sizes > 1)
1492
+ throw new TypeError('renderSVG() takes one of width, height and scale');
1493
+ const mode = givenWidth !== undefined ? 'width' : givenHeight !== undefined ? 'height' : 'scale';
1494
+ const size = finite(givenWidth ?? givenHeight ?? scale ?? 1, `SVG ${mode}`);
1495
+ if (mode === 'scale' && size <= 0)
1635
1496
  throw new RangeError('SVG scale must be > 0');
1636
- if (mode !== SVGScaleModes.SCALE && size < 1)
1637
- throw new RangeError('SVG size must be >= 1');
1497
+ if (mode !== 'scale' && size < 1)
1498
+ throw new RangeError(`SVG ${mode} must be >= 1`);
1638
1499
  if (typeof givenImages !== 'object' || givenImages === null || Array.isArray(givenImages) || givenImages instanceof Map)
1639
1500
  throw new TypeError('SVG images must be an object of hrefs to image data');
1640
1501
  const given = new Map();
@@ -1646,49 +1507,55 @@ export class Image {
1646
1507
  }
1647
1508
  const source = typeof svg === 'string' ? svg : view(svg);
1648
1509
  const images = new Map();
1510
+ const shown = (href) => JSON.stringify(href.length > 100 ? `${href.slice(0, 100)}...` : href);
1511
+ let imagePixels = Number(maxImagePixels);
1649
1512
  for (const { href, data } of svgRenderer.imageReferences(source)) {
1650
1513
  const value = given.get(href) ?? data;
1651
1514
  if (!value)
1652
1515
  continue;
1516
+ if (value instanceof Image) {
1517
+ images.set(href, { width: value.width, height: value.height, pixels: value.bitmap });
1518
+ continue;
1519
+ }
1520
+ const tooLarge = (cause) => new LimitError(`SVG: the image ${shown(href)} exceeds what's left of the ${maxImagePixels} pixels the SVG's images may decode to (the render options' maxImagePixels)`, { cause });
1521
+ if (!(imagePixels >= 1)) {
1522
+ images.set(href, { error: tooLarge() });
1523
+ continue;
1524
+ }
1653
1525
  try {
1654
- if (value instanceof Image) {
1655
- images.set(href, { width: value.width, height: value.height, pixels: value.bitmap });
1656
- }
1657
- else if (ImageType.getType(value) === 'gif') {
1658
- const decoded = gif.decode(view(value), true);
1659
- images.set(href, { width: decoded.width, height: decoded.height, pixels: gif.composite(decoded)[0].pixels });
1526
+ let decoded;
1527
+ if (ImageType.getType(value) === 'gif') {
1528
+ const gifData = await decoding(() => gif.decode(view(value), true, imagePixels));
1529
+ decoded = { width: gifData.width, height: gifData.height, pixels: gif.composite(gifData)[0].pixels };
1660
1530
  }
1661
1531
  else {
1662
- const image = await Image.decode(value);
1663
- images.set(href, { width: image.width, height: image.height, pixels: image.bitmap });
1532
+ const image = await Image.decode(value, { maxPixels: imagePixels });
1533
+ decoded = { width: image.width, height: image.height, pixels: image.bitmap };
1664
1534
  }
1535
+ imagePixels -= decoded.width * decoded.height;
1536
+ images.set(href, decoded);
1665
1537
  }
1666
- catch {
1538
+ catch (err) {
1539
+ images.set(href, { error: err instanceof LimitError ? tooLarge(err) : new Error(`SVG: the image ${shown(href)} can't be decoded`, { cause: err }) });
1667
1540
  }
1668
1541
  }
1669
- const { width, height, pixels } = svgRenderer.render(source, mode, size, images, fonts.map(font => view(font)));
1542
+ const { width, height, pixels } = svgRenderer.render(source, mode, size, images, (Array.isArray(fonts) ? fonts : [fonts]).map(font => view(font)), Number(maxPixels), Number(maxLayerPixels));
1670
1543
  const image = new Image(width, height);
1671
1544
  image.bitmap.set(pixels);
1672
1545
  return image;
1673
1546
  }
1674
- static async renderText(fontOrText, sizeOrOptions, textArgument, colorOrOptions = 0xffffffff, layoutArgument, styleArgument = {}) {
1675
- let font, size, text, options;
1676
- if (typeof fontOrText === 'string') {
1677
- if (!isOptions(sizeOrOptions) || sizeOrOptions.font === undefined)
1678
- throw new TypeError('renderText(text, options) needs the font in the options');
1679
- ({ font, size, ...options } = sizeOrOptions);
1680
- text = fontOrText;
1681
- }
1682
- else {
1683
- font = fontOrText;
1684
- size = sizeOrOptions;
1685
- text = textArgument;
1686
- options = isOptions(colorOrOptions) ? colorOrOptions : { ...styleArgument, color: colorOrOptions, layout: layoutArgument };
1687
- }
1688
- const { color = 0xffffffff, strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {} } = options;
1689
- const layout = options.layout instanceof TextLayout ? options.layout : new TextLayout(options.layout);
1547
+ static async renderText(text, options) {
1548
+ if (typeof text !== 'string' || !isOptions(options))
1549
+ throw new TypeError('renderText() takes the text and an options object, like renderText(\'Hello\', { font, size: 32 })');
1550
+ if (options.font === undefined)
1551
+ throw new TypeError('renderText(text, options) needs the font in the options');
1552
+ const { font, color = 0xffffffff, strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {}, maxPixels = MAX_PIXELS } = options;
1553
+ if (!(Number(maxPixels) > 0))
1554
+ throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
1555
+ const { maxWidth, maxHeight, wrapStyle, horizontalAlign, verticalAlign, wrapHardBreaks } = options;
1556
+ const layout = new TextLayout({ maxWidth, maxHeight, wrapStyle, horizontalAlign, verticalAlign, wrapHardBreaks });
1690
1557
  const axes = textRenderer.axisValues(variations);
1691
- size = finite(size, 'font size');
1558
+ const size = finite(options.size, 'font size');
1692
1559
  if (size < 0)
1693
1560
  throw new RangeError(`Invalid font size: ${size}`);
1694
1561
  if (finite(strokeWidth, 'stroke width') < 0)
@@ -1697,8 +1564,8 @@ export class Image {
1697
1564
  if (!fonts.length)
1698
1565
  throw new RangeError('No font given');
1699
1566
  const [r, g, b, a] = Colors.toRGBA(color);
1700
- const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features), axes);
1701
1567
  const pad = Math.ceil(strokeWidth);
1568
+ const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features), axes, Number(maxPixels), pad);
1702
1569
  const width = rendered.width + 2 * pad, height = rendered.height + 2 * pad;
1703
1570
  const coverage = new Uint8Array(width * height);
1704
1571
  for (let y = 0; y < rendered.height; y++)
@@ -1772,23 +1639,31 @@ function circleCoverage(px, py, cx, cy, radius) {
1772
1639
  return 0;
1773
1640
  return pixelCoverage(px, py, (x, y) => (x - cx) ** 2 + (y - cy) ** 2 <= radius * radius);
1774
1641
  }
1775
- const LEGACY_RESIZE_MODES = new Map([
1776
- ['RESIZE_NEAREST_NEIGHBOR', 'nearest-neighbor'], ['RESIZE_BILINEAR', 'bilinear'], ['RESIZE_BICUBIC', 'bicubic'], ['RESIZE_AREA', 'area']
1777
- ]);
1778
- export function resizeArguments(widthOrOptions, height, modeOrOptions) {
1779
- if (!isOptions(widthOrOptions))
1780
- return [widthOrOptions, height, modeOrOptions];
1781
- const { width, height: optionsHeight, ...options } = widthOrOptions;
1642
+ export function alignedPixels(pixels) {
1643
+ return pixels.byteOffset % 4 ? pixels.slice() : pixels;
1644
+ }
1645
+ export function resizeArguments(widthOrOptions, height, options) {
1646
+ if (!isOptions(widthOrOptions)) {
1647
+ checkOptions(options, 'resize(width, height, { mode: \'area\' })');
1648
+ return [finite(widthOrOptions, 'width'), finite(height, 'height'), options, 'fill'];
1649
+ }
1650
+ const { width, height: optionsHeight, fit = 'fill', ...rest } = widthOrOptions;
1782
1651
  if (width === undefined && optionsHeight === undefined)
1783
1652
  throw new TypeError('resize() needs a width, a height or both');
1784
- return [width ?? ResizeModes.AUTO, optionsHeight ?? ResizeModes.AUTO, options];
1653
+ if (!['fill', 'inside', 'contain', 'cover'].includes(fit))
1654
+ throw new TypeError(`fit must be 'fill', 'inside', 'contain' or 'cover', not ${String(fit)}`);
1655
+ return [width === undefined ? undefined : finite(width, 'width'), optionsHeight === undefined ? undefined : finite(optionsHeight, 'height'), rest, fit];
1656
+ }
1657
+ export function insideSize(width, height, boxWidth, boxHeight) {
1658
+ boxWidth = Math.floor(boxWidth);
1659
+ boxHeight = Math.floor(boxHeight);
1660
+ const scale = Math.min(boxWidth / width, boxHeight / height);
1661
+ return [Math.max(1, Math.min(boxWidth, Math.round(width * scale))), Math.max(1, Math.min(boxHeight, Math.round(height * scale)))];
1785
1662
  }
1786
- function resizeOptions(modeOrOptions) {
1787
- const options = isOptions(modeOrOptions) ? modeOrOptions : { mode: modeOrOptions };
1788
- const mode = options.mode ?? ResizeModes.BILINEAR;
1789
- return { mode: LEGACY_RESIZE_MODES.get(mode) ?? mode, fast: options.fast ?? true };
1663
+ const RESIZE_MODES = ['nearest-neighbor', 'bilinear', 'bicubic', 'area'];
1664
+ function resizeOptions(options) {
1665
+ return { mode: options?.mode === undefined ? 'bilinear' : oneOf(options.mode, RESIZE_MODES, 'resize mode'), fast: options?.fast ?? true };
1790
1666
  }
1791
- const LEGACY_SVG_MODES = new Map([[1, 'scale'], [2, 'width'], [3, 'height']]);
1792
1667
  const hardLight = (b, s) => s <= 0.5 ? b * 2 * s : 1 - (1 - b) * (1 - (2 * s - 1));
1793
1668
  const BLEND_MODES = {
1794
1669
  'normal': (_b, s) => s,
@@ -1811,12 +1686,7 @@ const BLEND_MODES = {
1811
1686
  'add': (b, s) => Math.min(1, b + s)
1812
1687
  };
1813
1688
  function gradientFunction(stops) {
1814
- if (!Array.isArray(stops))
1815
- return Colors.gradient(stops);
1816
- if (!stops.length)
1817
- throw new RangeError('Invalid gradient point count');
1818
- const colors = stops.length === 1 ? [stops[0], stops[0]] : stops;
1819
- return Colors.gradient(Object.fromEntries(colors.map((color, i) => [i / (colors.length - 1), color])));
1689
+ return Colors.gradient(stops);
1820
1690
  }
1821
1691
  const OUTLINE_WINDOW = 1;
1822
1692
  function outline(coverage, width, height, radius) {