imagescript 3.20.1 → 4.0.0-rc.1

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
@@ -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";
32
+ import { Colors, wrapHue, hue2rgb } from "./colors.js";
33
+ import { isOptions, checkOptions, finite, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
35
34
  import { MAX_PIXELS, 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));
@@ -131,34 +119,8 @@ export class Image {
131
119
  for (let x = 0; x < this.width; x++, offset += 4)
132
120
  yield [x, y, view.getUint32(offset, false)];
133
121
  }
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
122
  static linearGradient(width, height, options) {
123
+ checkOptions(options, 'Image.linearGradient(100, 50, { stops, angle: 90 })');
162
124
  const { stops, angle = 180 } = options;
163
125
  const color = gradientFunction(stops);
164
126
  finite(angle, 'angle');
@@ -173,6 +135,7 @@ export class Image {
173
135
  return image;
174
136
  }
175
137
  static radialGradient(width, height, options) {
138
+ checkOptions(options, 'Image.radialGradient(100, 50, { stops })');
176
139
  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
140
  const color = gradientFunction(stops);
178
141
  finite(cx, 'x');
@@ -186,27 +149,17 @@ export class Image {
186
149
  bitmap.setUint32(i, color(Math.hypot(x + 0.5 - cx, y + 0.5 - cy) / radius), false);
187
150
  return image;
188
151
  }
189
- static gradient(colors) {
190
- return Colors.gradient(colors);
191
- }
192
152
  getPixelAt(x, y) {
193
153
  x = ~~finite(x, 'x');
194
154
  y = ~~finite(y, 'y');
195
155
  this.__check_boundaries__(x, y);
196
156
  return this.__view__.getUint32((y * this.width + x) * 4, false);
197
157
  }
198
- getRGBAAt(x, y) {
158
+ setPixelAt(x, y, color) {
199
159
  x = ~~finite(x, 'x');
200
160
  y = ~~finite(y, 'y');
201
161
  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));
162
+ this.__set_pixel__(x, y, checkColor(color));
210
163
  return this;
211
164
  }
212
165
  __set_pixel__(x, y, pixelColor) {
@@ -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,32 +269,35 @@ 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
+ if (mode === 'nearest-neighbor')
334
299
  return this.__resize_nearest_neighbor__(width, height);
335
- const filter = mode === ResizeModes.BILINEAR ? TRIANGLE : mode === ResizeModes.BICUBIC ? CUBIC : mode === ResizeModes.AREA ? BOX : null;
300
+ const filter = mode === 'bilinear' ? TRIANGLE : mode === 'bicubic' ? CUBIC : mode === 'area' ? BOX : null;
336
301
  if (!filter)
337
302
  throw new Error('Invalid resize mode');
338
303
  const image = new Image(region?.width ?? width, region?.height ?? height);
@@ -353,6 +318,7 @@ export class Image {
353
318
  crop(x, y, width, height) {
354
319
  const bounds = this.__crop_bounds__(x, y, width, height);
355
320
  this.__crop_gain_map__(this, ...bounds);
321
+ this.__moved__?.(1, 1, bounds[0], bounds[1]);
356
322
  return this.__apply__(this.__crop__(...bounds));
357
323
  }
358
324
  __crop_gain_map__(target, x, y, width, height) {
@@ -363,7 +329,7 @@ export class Image {
363
329
  copy.__transform__(this.width, this.height, width, height, (X, Y) => [X + x, Y + y]);
364
330
  target.__gain_map__ = copy;
365
331
  }
366
- region(x, y, width, height) {
332
+ extract(x, y, width, height) {
367
333
  const bounds = this.__crop_bounds__(x, y, width, height);
368
334
  const image = this.__crop__(...bounds);
369
335
  this.__crop_gain_map__(image, ...bounds);
@@ -380,12 +346,14 @@ export class Image {
380
346
  throw new RangeError('Crop region does not overlap the image');
381
347
  return [left, top, right - left, bottom - top];
382
348
  }
383
- trim(colorOrOptions, optionsArgument = {}) {
384
- const { color, ...options } = isOptions(colorOrOptions) ? colorOrOptions : { ...optionsArgument, color: colorOrOptions ?? optionsArgument.color };
385
- const bounds = this.__trim_bounds__(color, options);
349
+ trim(options = {}) {
350
+ checkOptions(options, 'trim({ tolerance: 0.1 })');
351
+ const { color, ...rest } = options;
352
+ const bounds = this.__trim_bounds__(color, rest);
386
353
  if (!bounds)
387
354
  return this;
388
355
  this.__crop_gain_map__(this, ...bounds);
356
+ this.__moved__?.(1, 1, bounds[0], bounds[1]);
389
357
  return this.__apply__(this.__crop__(...bounds));
390
358
  }
391
359
  __trim_bounds__(color, { tolerance = 0 }) {
@@ -441,84 +409,9 @@ export class Image {
441
409
  }
442
410
  return image;
443
411
  }
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 };
412
+ cropCircle(options = {}) {
413
+ checkOptions(options, 'cropCircle({ size: \'cover\' })');
414
+ const { size = 'contain', feathering = 0 } = options;
522
415
  finite(feathering, 'feathering');
523
416
  if (size !== 'contain' && size !== 'cover')
524
417
  throw new TypeError(`Invalid circle size: ${String(size)}`);
@@ -566,70 +459,64 @@ export class Image {
566
459
  }
567
460
  return this;
568
461
  }
569
- opacity(opacity, absoluteOrOptions = false) {
570
- const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions;
462
+ opacity(opacity) {
571
463
  opacity = finite(opacity, 'opacity value');
572
464
  if (opacity < 0)
573
465
  throw new RangeError('Invalid opacity value');
574
- this.__set_channel_value__(opacity, absolute, 3);
466
+ this.__set_channel_value__(opacity, 3);
575
467
  return this;
576
468
  }
577
- red(factor, absoluteOrOptions = false) {
469
+ red(factor) {
578
470
  if (this.__gain_map__)
579
- return this.__recolor__(image => image.red(factor, absoluteOrOptions));
580
- const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions;
471
+ return this.__recolor__(image => image.red(factor));
581
472
  factor = finite(factor, 'red factor');
582
473
  if (factor < 0)
583
474
  throw new RangeError('Invalid red factor');
584
- this.__set_channel_value__(factor, absolute, 0);
475
+ this.__set_channel_value__(factor, 0);
585
476
  return this;
586
477
  }
587
- green(factor, absoluteOrOptions = false) {
478
+ green(factor) {
588
479
  if (this.__gain_map__)
589
- return this.__recolor__(image => image.green(factor, absoluteOrOptions));
590
- const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions;
480
+ return this.__recolor__(image => image.green(factor));
591
481
  factor = finite(factor, 'green factor');
592
482
  if (factor < 0)
593
483
  throw new RangeError('Invalid green factor');
594
- this.__set_channel_value__(factor, absolute, 1);
484
+ this.__set_channel_value__(factor, 1);
595
485
  return this;
596
486
  }
597
- blue(factor, absoluteOrOptions = false) {
487
+ blue(factor) {
598
488
  if (this.__gain_map__)
599
- return this.__recolor__(image => image.blue(factor, absoluteOrOptions));
600
- const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions;
489
+ return this.__recolor__(image => image.blue(factor));
601
490
  factor = finite(factor, 'blue factor');
602
491
  if (factor < 0)
603
492
  throw new RangeError('Invalid blue factor');
604
- this.__set_channel_value__(factor, absolute, 2);
493
+ this.__set_channel_value__(factor, 2);
605
494
  return this;
606
495
  }
607
- __set_channel_value__(value, absolute, offset) {
496
+ __set_channel_value__(value, offset) {
608
497
  for (let i = offset; i < this.bitmap.length; i += 4)
609
- this.bitmap[i] = value * (absolute ? 255 : this.bitmap[i]);
498
+ this.bitmap[i] = value * this.bitmap[i];
610
499
  }
611
- lightness(value, absoluteOrOptions = false) {
500
+ lightness(factor) {
612
501
  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) {
502
+ return this.__recolor__(image => image.lightness(factor));
503
+ factor = finite(factor, 'lightness factor');
504
+ if (factor < 0)
505
+ throw new RangeError('Invalid lightness factor');
506
+ return this.__map_hsla__(c => { c.l = factor * c.l; });
507
+ }
508
+ saturation(factor) {
621
509
  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;
510
+ return this.__recolor__(image => image.saturation(factor), true);
511
+ factor = finite(factor, 'saturation factor');
512
+ if (factor < 0)
513
+ throw new RangeError('Invalid saturation factor');
514
+ return this.__map_hsla__(c => { c.s = factor * c.s; });
515
+ }
516
+ composite(source, options = {}) {
517
+ checkOptions(options, 'composite(source, { x: 10, y: 20 })');
631
518
  const { opacity = 1, mode = 'normal' } = options;
632
- let x = isOptions(xOrOptions) ? xOrOptions.x ?? 0 : xOrOptions, y = isOptions(xOrOptions) ? xOrOptions.y ?? 0 : yArgument;
519
+ let x = options.x ?? 0, y = options.y ?? 0;
633
520
  x = finite(x, 'x') | 0;
634
521
  y = finite(y, 'y') | 0;
635
522
  if (isNaN(opacity) || opacity < 0 || opacity > 1)
@@ -678,7 +565,7 @@ export class Image {
678
565
  const ownMap = this.__gain_map__, sourceMap = source.__gain_map__;
679
566
  this.__gain_map__ = source.__gain_map__ = null;
680
567
  try {
681
- this.composite(source, x, y, { opacity, mode });
568
+ this.composite(source, { x, y, opacity, mode });
682
569
  }
683
570
  finally {
684
571
  this.__gain_map__ = ownMap;
@@ -729,7 +616,7 @@ export class Image {
729
616
  }
730
617
  out[c] = share * Hs + (1 - share) * Hd;
731
618
  }
732
- }, map.channels === 1 && (!sourceMap || sourceMap.channels === 1), Math.max(0, ...(sourceMap?.gainMapMax ?? [0])));
619
+ }, map.channels === 1 && (!sourceMap || sourceMap.channels === 1), Math.max(0, ...(sourceMap?.__max__ ?? [0])));
733
620
  return this;
734
621
  }
735
622
  __blend__(source, x, y, opacity, blend) {
@@ -860,9 +747,10 @@ export class Image {
860
747
  return this;
861
748
  }
862
749
  quantize(options = {}) {
750
+ checkOptions(options, 'image.quantize({ colors: 16 })');
863
751
  if (typeof options !== 'object' || options === null)
864
752
  throw new TypeError('quantize takes an options object');
865
- const { colors, palette, dither = 'none', ditherStrength = 1 } = options;
753
+ const { colors, palette, dither = 'floyd-steinberg', ditherStrength = 0.85 } = options;
866
754
  if (colors !== undefined && palette !== undefined)
867
755
  throw new TypeError('quantize takes colors or palette, not both');
868
756
  let fixed = null, count = 256;
@@ -882,16 +770,10 @@ export class Image {
882
770
  });
883
771
  fixed = packed;
884
772
  }
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}`);
773
+ const checked = quantize.paletteOptions(palette === undefined ? colors : undefined, dither, ditherStrength);
774
+ if (checked.colors !== undefined)
775
+ count = checked.colors;
776
+ const strength = checked.strength;
895
777
  const reduce = (image) => {
896
778
  const bytes = image.__bytes__();
897
779
  const table = fixed ?? quantize.buildPalette(bytes, count, 1);
@@ -929,6 +811,7 @@ export class Image {
929
811
  return this;
930
812
  }
931
813
  transform(matrix, options = {}) {
814
+ checkOptions(options, 'image.transform([1, 0, 0, 1, 0, 0], { expand: false })');
932
815
  if (matrix === null || typeof matrix !== 'object' || matrix.length !== 6)
933
816
  throw new RangeError('A transform has 6 values: [a, b, c, d, e, f]');
934
817
  const values = Array.from({ length: 6 }, (_, i) => finite(typeof matrix[i] === 'number' ? matrix[i] : NaN, 'transform value'));
@@ -957,15 +840,6 @@ export class Image {
957
840
  outHeight = Math.max(1, Math.round(maxY - minY));
958
841
  left = minX - (outWidth - (maxX - minX)) / 2;
959
842
  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
843
  if (outWidth * outHeight > MAX_PIXELS)
970
844
  throw new RangeError(`The transformed image would have ${outWidth}x${outHeight} pixels, more than the ${MAX_PIXELS} allowed`);
971
845
  }
@@ -976,12 +850,11 @@ export class Image {
976
850
  const x = X + left, y = Y + top;
977
851
  return [inverse[0] * x + inverse[2] * y + inverse[4], inverse[1] * x + inverse[3] * y + inverse[5]];
978
852
  }, scale);
979
- this.__apply__(out);
980
- if (left || top)
981
- this.__grown__(-Math.round(left), -Math.round(top));
982
- return this;
853
+ this.__moved__?.(1, 1, left, top);
854
+ return this.__apply__(out);
983
855
  }
984
856
  dropShadow(options = {}) {
857
+ checkOptions(options, 'image.dropShadow({ blur: 8 })');
985
858
  const { x = 0, y = 0, blur = 0, spread = 0, color = 0x00000080, expand = true } = options;
986
859
  finite(x, 'x');
987
860
  finite(y, 'y');
@@ -1014,15 +887,15 @@ export class Image {
1014
887
  bitmap[i * 4 + 2] = b;
1015
888
  }
1016
889
  }
1017
- const room = this.__room__();
1018
890
  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))),
891
+ left: Math.max(0, Math.ceil(reach - x)),
892
+ top: Math.max(0, Math.ceil(reach - y)),
1021
893
  right: Math.max(0, Math.ceil(reach + x)),
1022
894
  bottom: Math.max(0, Math.ceil(reach + y))
1023
895
  } : { left: 0, top: 0, right: 0, bottom: 0 });
1024
896
  }
1025
897
  outline(options = {}) {
898
+ checkOptions(options, 'image.outline({ width: 4 })');
1026
899
  const { width = 1, color = 0x000000ff, expand = true } = options;
1027
900
  if (finite(width, 'outline width') < 0)
1028
901
  throw new RangeError('Invalid outline width');
@@ -1042,9 +915,9 @@ export class Image {
1042
915
  bitmap[i * 4 + 2] = b;
1043
916
  bitmap[i * 4 + 3] = stroke[i] * (1 - coverage[i] / 255) * a;
1044
917
  }
1045
- const room = this.__room__(), grow = Math.ceil(width);
918
+ const grow = Math.ceil(width);
1046
919
  return this.__under__(layer, -margin, -margin, expand
1047
- ? { left: Math.min(room.left, grow), top: Math.min(room.top, grow), right: grow, bottom: grow }
920
+ ? { left: grow, top: grow, right: grow, bottom: grow }
1048
921
  : { left: 0, top: 0, right: 0, bottom: 0 });
1049
922
  }
1050
923
  __shape_layer__(margin) {
@@ -1068,18 +941,12 @@ export class Image {
1068
941
  this.__gain_map__ = map;
1069
942
  }
1070
943
  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) {
944
+ this.__moved__?.(1, 1, -left, -top);
945
+ return this.__apply__(result);
1080
946
  }
1081
- sharpen(amountOrOptions = 1, radiusArgument = 1) {
1082
- const { amount = 1, radius = 1 } = isOptions(amountOrOptions) ? amountOrOptions : { amount: amountOrOptions, radius: radiusArgument };
947
+ sharpen(options = {}) {
948
+ checkOptions(options, 'sharpen({ amount: 0.5 })');
949
+ const { amount = 1, radius = 1 } = options;
1083
950
  if (!Number.isFinite(amount) || amount < 0)
1084
951
  throw new RangeError('Invalid sharpen amount');
1085
952
  if (!Number.isFinite(radius) || radius <= 0)
@@ -1122,9 +989,9 @@ export class Image {
1122
989
  throw new RangeError('Invalid gamma');
1123
990
  return this.__map_channels__(v => 255 * (v / 255) ** (1 / gamma));
1124
991
  }
1125
- greyscale() {
992
+ grayscale() {
1126
993
  if (this.__gain_map__)
1127
- return this.__recolor__(image => image.greyscale(), true);
994
+ return this.__recolor__(image => image.grayscale(), true);
1128
995
  const bitmap = this.bitmap;
1129
996
  for (let i = 0; i < bitmap.length; i += 4)
1130
997
  bitmap[i] = bitmap[i + 1] = bitmap[i + 2] = bitmap[i] * 19595 + bitmap[i + 1] * 38470 + bitmap[i + 2] * 7471 + 0x8000 >> 16;
@@ -1142,8 +1009,9 @@ export class Image {
1142
1009
  }
1143
1010
  return this;
1144
1011
  }
1145
- colorToAlpha(colorOrOptions, optionsArgument = {}) {
1146
- const { color: colorOption, transparencyThreshold = 0, opacityThreshold = 1 } = isOptions(colorOrOptions) ? colorOrOptions : { ...optionsArgument, color: colorOrOptions ?? optionsArgument.color };
1012
+ colorToAlpha(options = {}) {
1013
+ checkOptions(options, 'colorToAlpha({ color: 0xffffffff })');
1014
+ const { color: colorOption, transparencyThreshold = 0, opacityThreshold = 1 } = options;
1147
1015
  let color = colorOption;
1148
1016
  if (!(transparencyThreshold >= 0 && opacityThreshold <= 1 && transparencyThreshold < opacityThreshold))
1149
1017
  throw new RangeError('Invalid thresholds, they have to satisfy 0 <= transparencyThreshold < opacityThreshold <= 1');
@@ -1193,18 +1061,21 @@ export class Image {
1193
1061
  return Colors.fromRGBA(0, 0, 0, 0xff);
1194
1062
  return Colors.fromRGBA(Math.round(r / weight), Math.round(g / weight), Math.round(b / weight), 0xff);
1195
1063
  }
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 };
1064
+ dominantColor(options = {}) {
1065
+ checkOptions(options, 'dominantColor({ ignoreBlack: false })');
1066
+ const { ignoreBlack = true, ignoreWhite = true, threshold: bwThreshold = 0xf } = options;
1199
1067
  const threshold = Math.min(64, Math.max(0, finite(bwThreshold, 'threshold'))) * 4;
1200
1068
  const pixels = this.__bytes__();
1201
1069
  const color = quantize.dominantColor(pixels, (r, g, b) => !(ignoreBlack && Math.max(r, g, b) < threshold) && !(ignoreWhite && Math.min(r, g, b) > 255 - threshold))
1202
1070
  || quantize.dominantColor(pixels, () => true);
1203
1071
  return color ? Colors.fromRGB(...color) : Colors.fromRGBA(0, 0, 0, 0xff);
1204
1072
  }
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;
1073
+ rotate(angle, options = {}) {
1074
+ checkOptions(options, 'rotate(angle, { expand: false })');
1075
+ const { expand = true, mode = 'bilinear' } = options;
1076
+ if (!TRANSFORM_MODES.includes(mode))
1077
+ throw new TypeError(`rotate mode must be one of ${TRANSFORM_MODES.map(name => `'${name}'`).join(', ')}, not ${String(mode)}`);
1078
+ angle = ((-finite(angle, 'angle') % 360) + 360) % 360;
1208
1079
  if (angle === 0)
1209
1080
  return this;
1210
1081
  const { width, height } = this;
@@ -1230,68 +1101,19 @@ export class Image {
1230
1101
  dst[x * height + height - 1 - y] = i;
1231
1102
  }
1232
1103
  rotateGainMap(out.width, out.height);
1104
+ this.__moved__?.(1, 1, (width - out.width) / 2, (height - out.height) / 2);
1233
1105
  return this.__apply__(out);
1234
1106
  }
1235
1107
  const rad = angle * Math.PI / 180;
1236
1108
  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;
1109
+ const outWidth = expand ? Math.round(Math.abs(width * cos) + Math.abs(height * sin)) : width;
1110
+ const outHeight = expand ? Math.round(Math.abs(width * sin) + Math.abs(height * cos)) : height;
1239
1111
  const out = new Image(outWidth, outHeight);
1240
1112
  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
- }
1113
+ const inverse = [cos, sin, -sin, cos,
1114
+ width / 2 - cos * outWidth / 2 + sin * outHeight / 2, height / 2 - sin * outWidth / 2 - cos * outHeight / 2];
1115
+ sampleAffine(this.bitmap, width, height, out.bitmap, outWidth, outHeight, inverse, 0, 0, mode);
1116
+ this.__moved__?.(1, 1, (width - outWidth) / 2, (height - outHeight) / 2);
1295
1117
  return this.__apply__(out);
1296
1118
  }
1297
1119
  flip(direction) {
@@ -1352,8 +1174,9 @@ export class Image {
1352
1174
  this.__u32__ = image.__u32__;
1353
1175
  return this;
1354
1176
  }
1355
- roundCorners(radiusOrOptions) {
1356
- let radius = (isOptions(radiusOrOptions) ? radiusOrOptions.radius : radiusOrOptions) ?? Math.min(this.width, this.height) / 4;
1177
+ roundCorners(options = {}) {
1178
+ checkOptions(options, 'roundCorners({ radius: 10 })');
1179
+ let radius = options.radius ?? Math.min(this.width, this.height) / 4;
1357
1180
  radius = finite(radius, 'radius');
1358
1181
  radius = Math.max(0, Math.min(radius, this.width / 2, this.height / 2));
1359
1182
  const size = Math.ceil(radius);
@@ -1369,8 +1192,9 @@ export class Image {
1369
1192
  }
1370
1193
  return this;
1371
1194
  }
1372
- fisheye(strengthOrOptions) {
1373
- const strength = finite((isOptions(strengthOrOptions) ? strengthOrOptions.strength : strengthOrOptions) ?? 2, 'strength');
1195
+ fisheye(options = {}) {
1196
+ checkOptions(options, 'fisheye({ strength: 3 })');
1197
+ const strength = finite(options.strength ?? 2, 'strength');
1374
1198
  const r = new Image(this.width, this.height);
1375
1199
  const w = this.width;
1376
1200
  const h = this.height;
@@ -1402,26 +1226,23 @@ export class Image {
1402
1226
  });
1403
1227
  return this.__apply__(r);
1404
1228
  }
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;
1229
+ async encodePNG(options = {}) {
1230
+ checkOptions(options, 'encodePNG({ compression: 9, metadata: { author: \'me\' } })');
1231
+ const { compression = 4, metadata = {} } = options;
1413
1232
  return png.encodeRGBA(this.__bytes__(), this.width, this.height, compressionLevel(compression), pngText(resolveMetadata(metadata)));
1414
1233
  }
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 };
1234
+ async encodeJPEG(options = {}) {
1235
+ checkOptions(options, 'encodeJPEG({ quality: 80 })');
1236
+ const { quality = 90, subsampling, background = 0x000000ff, metadata = {}, gainMap: gainMapOption = true } = options;
1237
+ if (subsampling !== undefined && subsampling !== '4:4:4' && subsampling !== '4:2:0')
1238
+ throw new TypeError(`subsampling must be '4:4:4' or '4:2:0', not ${String(subsampling)}`);
1239
+ const backgroundColor = checkColor(background, 'background');
1420
1240
  const m = resolveMetadata(metadata);
1421
- const base = { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined };
1422
- const gainMap = this.__gain_map__;
1241
+ const base = { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined, subsampling };
1242
+ const source = this.__flattened__(backgroundColor, gainMapOption !== false) ?? this;
1243
+ const gainMap = source.__gain_map__;
1423
1244
  if (!gainMap || gainMapOption === false)
1424
- return jpeg.encode(this.__bytes__(), this.width, this.height, finite(quality, 'quality'), base);
1245
+ return jpeg.encode(source.__bytes__(), source.width, source.height, finite(quality, 'quality'), base);
1425
1246
  const { quality: mapQuality, scale } = typeof gainMapOption === 'object' && gainMapOption !== null ? gainMapOption : {};
1426
1247
  let width, height;
1427
1248
  if (scale !== undefined) {
@@ -1433,10 +1254,26 @@ export class Image {
1433
1254
  }
1434
1255
  const params = gainMap.__params__();
1435
1256
  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) });
1257
+ const primary = jpeg.encode(source.__bytes__(), source.width, source.height, finite(quality, 'quality'), { ...base, segments: gainMapCodec.primarySegments(map.length) });
1437
1258
  return gainMapCodec.finish(primary, map);
1438
1259
  }
1439
- async encodeWebP({ quality, effort = 2, sharpYuv = false, alphaQuality = 100, threads = defaultThreads(), metadata = {} } = {}) {
1260
+ __flattened__(background, withGainMap) {
1261
+ const pixels = this.bitmap;
1262
+ let opaque = true;
1263
+ for (let i = 3; i < pixels.length && opaque; i += 4)
1264
+ opaque = pixels[i] === 255;
1265
+ if (opaque)
1266
+ return null;
1267
+ const flat = new Image(this.width, this.height).fill((background | 0xff) >>> 0);
1268
+ if (withGainMap || !this.__gain_map__)
1269
+ return flat.composite(this);
1270
+ const withoutMap = this.clone();
1271
+ withoutMap.gainMap = null;
1272
+ return flat.composite(withoutMap);
1273
+ }
1274
+ async encodeWebP(options = {}) {
1275
+ checkOptions(options, 'image.encodeWebP({ quality: 80 })');
1276
+ const { quality, effort = 2, sharpYuv = false, alphaQuality = 100, threads = defaultThreads(), metadata = {} } = options;
1440
1277
  checkThreads(threads);
1441
1278
  const exif = exifData(resolveMetadata(metadata));
1442
1279
  const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
@@ -1444,17 +1281,30 @@ export class Image {
1444
1281
  return webp.encode(this.__bytes__(), this.width, this.height, exif, threads, effort);
1445
1282
  return webp.encodeLossy(this.__bytes__(), this.width, this.height, lossy, exif);
1446
1283
  }
1447
- async encodeTGA({ metadata = {} } = {}) {
1284
+ async encodeTGA(options = {}) {
1285
+ checkOptions(options, 'image.encodeTGA({ metadata })');
1286
+ const { metadata = {} } = options;
1448
1287
  const { author, comment, creationTime: time, software } = resolveMetadata(metadata);
1449
1288
  return tga.encode(this.__bytes__(), this.width, this.height, { author, comment, time, software });
1450
1289
  }
1290
+ async encodeGIF(options = {}) {
1291
+ checkOptions(options, 'image.encodeGIF({ colors: 64 })');
1292
+ const { colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85, metadata = {} } = options;
1293
+ const palette = quantize.paletteOptions(colors, dither, ditherStrength);
1294
+ if (this.width > 0xffff || this.height > 0xffff)
1295
+ throw new RangeError(`GIF: images can be at most 65535 pixels wide and high, not ${this.width}x${this.height}`);
1296
+ const frame = { x: 0, y: 0, width: this.width, height: this.height, delay: 0, dispose: 1, pixels: this.__bytes__() };
1297
+ 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)));
1298
+ }
1451
1299
  async encodeBMP() {
1452
1300
  return bmp.encode(this.__bytes__(), this.width, this.height);
1453
1301
  }
1454
1302
  async encodeQOI() {
1455
1303
  return qoi.encode(this.__bytes__(), this.width, this.height);
1456
1304
  }
1457
- async encodeAVIF({ quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true } = {}) {
1305
+ async encodeAVIF(options = {}) {
1306
+ checkOptions(options, 'image.encodeAVIF({ quality: 60 })');
1307
+ const { quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true } = options;
1458
1308
  checkEffort(effort, 2);
1459
1309
  checkThreads(threads);
1460
1310
  if (subsampling !== '4:4:4' && subsampling !== '4:2:0')
@@ -1481,7 +1331,9 @@ export class Image {
1481
1331
  }
1482
1332
  return { pixels: map.__bytes__(), width: map.width, height: map.height, params: gainMap.__params__(), quality: mapQuality };
1483
1333
  }
1484
- async encodeJXL({ quality, effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true } = {}) {
1334
+ async encodeJXL(options = {}) {
1335
+ checkOptions(options, 'image.encodeJXL({ quality: 90 })');
1336
+ const { quality, effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true } = options;
1485
1337
  checkEffort(effort, 2);
1486
1338
  checkThreads(threads);
1487
1339
  const distanceOf = (q) => q >= 100 ? 0 : q >= 30 ? 0.1 + (100 - q) * 0.09 : 53 / 3000 * q * q - 23 / 20 * q + 25;
@@ -1493,6 +1345,7 @@ export class Image {
1493
1345
  return netpbm.encode(this.__bytes__(), this.width, this.height);
1494
1346
  }
1495
1347
  static async decode(input, options = {}) {
1348
+ checkOptions(options, 'Image.decode(data, { maxPixels: 1e8 })');
1496
1349
  const { applyOrientation = true, applyColorProfile = true, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = defaultThreads(), gainMap = true } = options;
1497
1350
  checkThreads(threads);
1498
1351
  if (!(Number(maxPixels) > 0))
@@ -1509,9 +1362,10 @@ export class Image {
1509
1362
  if (ImageType.isTIFF(dataView))
1510
1363
  return tiff.decode(data, maxPixels);
1511
1364
  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);
1365
+ if (!webp.isAnimated(data))
1366
+ return webp.decode(data, maxPixels);
1367
+ const animation = webp.decodeAnimation(data, true, maxPixels);
1368
+ return { width: animation.width, height: animation.height, pixels: webp.composite(animation)[0].pixels, orientation: animation.orientation, icc: animation.icc };
1515
1369
  }
1516
1370
  const bitmap = async (decoded) => {
1517
1371
  if (!('embedded' in decoded))
@@ -1525,7 +1379,7 @@ export class Image {
1525
1379
  return jxl.decode(data, maxPixels, toneMapping, threads, gainMap);
1526
1380
  if (ImageType.isBMP(dataView))
1527
1381
  return bitmap(bmp.decode(data, maxPixels));
1528
- if (ImageType.isICO(dataView))
1382
+ if (ImageType.isICO(dataView) || ImageType.isCUR(dataView))
1529
1383
  return bitmap(ico.decode(data, maxPixels));
1530
1384
  if (ImageType.isQOI(dataView))
1531
1385
  return qoi.decode(data, maxPixels);
@@ -1535,8 +1389,13 @@ export class Image {
1535
1389
  return hdr.decode(data, maxPixels, toneMapping);
1536
1390
  if (ImageType.isTGA(dataView))
1537
1391
  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)');
1392
+ if (ImageType.isGIF(dataView)) {
1393
+ const gifData = gif.decode(data, true, maxPixels);
1394
+ const [first] = gif.composite(gifData);
1395
+ if (!first)
1396
+ throw new Error('GIF: no frames');
1397
+ return { width: gifData.width, height: gifData.height, pixels: first.pixels };
1398
+ }
1540
1399
  throw new Error('Unsupported image type');
1541
1400
  });
1542
1401
  if (applyColorProfile) {
@@ -1622,19 +1481,20 @@ export class Image {
1622
1481
  }
1623
1482
  return this.__apply__(out);
1624
1483
  }
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)
1484
+ static async renderSVG(svg, options = {}) {
1485
+ checkOptions(options, 'renderSVG(svg, { width: 512 })');
1486
+ const { width: givenWidth, height: givenHeight, scale, maxPixels = MAX_PIXELS, fonts = [], images: givenImages = {} } = options;
1487
+ if (!(Number(maxPixels) > 0))
1488
+ throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
1489
+ const sizes = [givenWidth, givenHeight, scale].filter(value => value !== undefined).length;
1490
+ if (sizes > 1)
1491
+ throw new TypeError('renderSVG() takes one of width, height and scale');
1492
+ const mode = givenWidth !== undefined ? 'width' : givenHeight !== undefined ? 'height' : 'scale';
1493
+ const size = finite(givenWidth ?? givenHeight ?? scale ?? 1, `SVG ${mode}`);
1494
+ if (mode === 'scale' && size <= 0)
1635
1495
  throw new RangeError('SVG scale must be > 0');
1636
- if (mode !== SVGScaleModes.SCALE && size < 1)
1637
- throw new RangeError('SVG size must be >= 1');
1496
+ if (mode !== 'scale' && size < 1)
1497
+ throw new RangeError(`SVG ${mode} must be >= 1`);
1638
1498
  if (typeof givenImages !== 'object' || givenImages === null || Array.isArray(givenImages) || givenImages instanceof Map)
1639
1499
  throw new TypeError('SVG images must be an object of hrefs to image data');
1640
1500
  const given = new Map();
@@ -1655,40 +1515,32 @@ export class Image {
1655
1515
  images.set(href, { width: value.width, height: value.height, pixels: value.bitmap });
1656
1516
  }
1657
1517
  else if (ImageType.getType(value) === 'gif') {
1658
- const decoded = gif.decode(view(value), true);
1518
+ const decoded = gif.decode(view(value), true, maxPixels);
1659
1519
  images.set(href, { width: decoded.width, height: decoded.height, pixels: gif.composite(decoded)[0].pixels });
1660
1520
  }
1661
1521
  else {
1662
- const image = await Image.decode(value);
1522
+ const image = await Image.decode(value, { maxPixels });
1663
1523
  images.set(href, { width: image.width, height: image.height, pixels: image.bitmap });
1664
1524
  }
1665
1525
  }
1666
1526
  catch {
1667
1527
  }
1668
1528
  }
1669
- const { width, height, pixels } = svgRenderer.render(source, mode, size, images, fonts.map(font => view(font)));
1529
+ const { width, height, pixels } = svgRenderer.render(source, mode, size, images, (Array.isArray(fonts) ? fonts : [fonts]).map(font => view(font)), maxPixels);
1670
1530
  const image = new Image(width, height);
1671
1531
  image.bitmap.set(pixels);
1672
1532
  return image;
1673
1533
  }
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);
1534
+ static async renderText(text, options) {
1535
+ if (typeof text !== 'string' || !isOptions(options))
1536
+ throw new TypeError('renderText() takes the text and an options object, like renderText(\'Hello\', { font, size: 32 })');
1537
+ if (options.font === undefined)
1538
+ throw new TypeError('renderText(text, options) needs the font in the options');
1539
+ const { font, color = 0xffffffff, strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {} } = options;
1540
+ const { maxWidth, maxHeight, wrapStyle, horizontalAlign, verticalAlign, wrapHardBreaks } = options;
1541
+ const layout = new TextLayout({ maxWidth, maxHeight, wrapStyle, horizontalAlign, verticalAlign, wrapHardBreaks });
1690
1542
  const axes = textRenderer.axisValues(variations);
1691
- size = finite(size, 'font size');
1543
+ const size = finite(options.size, 'font size');
1692
1544
  if (size < 0)
1693
1545
  throw new RangeError(`Invalid font size: ${size}`);
1694
1546
  if (finite(strokeWidth, 'stroke width') < 0)
@@ -1772,23 +1624,27 @@ function circleCoverage(px, py, cx, cy, radius) {
1772
1624
  return 0;
1773
1625
  return pixelCoverage(px, py, (x, y) => (x - cx) ** 2 + (y - cy) ** 2 <= radius * radius);
1774
1626
  }
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;
1627
+ export function resizeArguments(widthOrOptions, height, options) {
1628
+ if (!isOptions(widthOrOptions)) {
1629
+ checkOptions(options, 'resize(width, height, { mode: \'area\' })');
1630
+ return [finite(widthOrOptions, 'width'), finite(height, 'height'), options, 'fill'];
1631
+ }
1632
+ const { width, height: optionsHeight, fit = 'fill', ...rest } = widthOrOptions;
1782
1633
  if (width === undefined && optionsHeight === undefined)
1783
1634
  throw new TypeError('resize() needs a width, a height or both');
1784
- return [width ?? ResizeModes.AUTO, optionsHeight ?? ResizeModes.AUTO, options];
1635
+ if (!['fill', 'inside', 'contain', 'cover'].includes(fit))
1636
+ throw new TypeError(`fit must be 'fill', 'inside', 'contain' or 'cover', not ${String(fit)}`);
1637
+ return [width === undefined ? undefined : finite(width, 'width'), optionsHeight === undefined ? undefined : finite(optionsHeight, 'height'), rest, fit];
1638
+ }
1639
+ export function insideSize(width, height, boxWidth, boxHeight) {
1640
+ boxWidth = Math.floor(boxWidth);
1641
+ boxHeight = Math.floor(boxHeight);
1642
+ const scale = Math.min(boxWidth / width, boxHeight / height);
1643
+ return [Math.max(1, Math.min(boxWidth, Math.round(width * scale))), Math.max(1, Math.min(boxHeight, Math.round(height * scale)))];
1785
1644
  }
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 };
1645
+ function resizeOptions(options) {
1646
+ return { mode: options?.mode ?? 'bilinear', fast: options?.fast ?? true };
1790
1647
  }
1791
- const LEGACY_SVG_MODES = new Map([[1, 'scale'], [2, 'width'], [3, 'height']]);
1792
1648
  const hardLight = (b, s) => s <= 0.5 ? b * 2 * s : 1 - (1 - b) * (1 - (2 * s - 1));
1793
1649
  const BLEND_MODES = {
1794
1650
  'normal': (_b, s) => s,
@@ -1811,12 +1667,7 @@ const BLEND_MODES = {
1811
1667
  'add': (b, s) => Math.min(1, b + s)
1812
1668
  };
1813
1669
  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])));
1670
+ return Colors.gradient(stops);
1820
1671
  }
1821
1672
  const OUTLINE_WINDOW = 1;
1822
1673
  function outline(coverage, width, height, radius) {