imagescript 4.0.0-rc.2 → 4.0.0-rc.3

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.d.ts CHANGED
@@ -68,11 +68,6 @@ export type ResizeToOptions = ResizeOptions & ({
68
68
  export interface ResizeOptions {
69
69
  /** The resizing mode. Default: `'bilinear'` */
70
70
  mode?: ResizeMode;
71
- /**
72
- * Whether to use faster, lower-precision arithmetic. It can cause small color differences, especially around
73
- * transparent edges. Only affects `'bilinear'` and `'area'` resizing. Default: `true`
74
- */
75
- fast?: boolean;
76
71
  }
77
72
  /** Options of {@link Image.sharpen} */
78
73
  export interface SharpenOptions {
@@ -87,31 +82,40 @@ export interface SharpenOptions {
87
82
  * errors to nearby pixels; `'ordered'` uses a repeating pattern. Atkinson tends to give a higher-contrast result.
88
83
  */
89
84
  export type DitherMethod = 'none' | 'floyd-steinberg' | 'atkinson' | 'ordered';
90
- /** Options of {@link Image.quantize}: either `colors` or `palette`, and the dithering */
91
- export interface QuantizeOptions {
85
+ /** How colors are dithered when they are reduced to a palette: options of {@link Image.quantize} and the GIF encoders */
86
+ export interface DitherOptions {
87
+ /**
88
+ * How to spread small color changes across nearby pixels to make gradients look smoother with few colors, see
89
+ * {@link DitherMethod}. Default: `'floyd-steinberg'`
90
+ */
91
+ dither?: DitherMethod;
92
+ /** How strongly to apply dithering: `0` disables it (like `'none'`); `1` applies it fully. Default: `0.85` */
93
+ ditherStrength?: number;
94
+ }
95
+ /**
96
+ * Options of {@link Image.quantize}: either `colors` or `palette` (TypeScript reports a call with both), and the
97
+ * dithering
98
+ */
99
+ export type QuantizeOptions = DitherOptions & ({
92
100
  /**
93
101
  * The maximum number of colors to keep (2-256). Images with fewer distinct colors keep them exactly; otherwise
94
102
  * ImageScript chooses a smaller set of representative colors. Give `palette` instead to choose exact colors.
95
- * Default: `256`. Give `colors` or `palette`, not both
103
+ * Default: `256`
96
104
  */
97
105
  colors?: number;
106
+ /** Not with `colors`: give one of them */
107
+ palette?: never;
108
+ } | {
98
109
  /**
99
110
  * A fixed palette (1-256 colors, e.g. a Game Boy's four greens). Every pixel is changed to the nearest palette
100
- * color by its red, green and blue values; transparency in palette colors is ignored. Give `palette` or `colors`,
101
- * not both
102
- */
103
- palette?: Color[];
104
- /**
105
- * How to spread small color changes across nearby pixels to make gradients look smoother with few colors, see
106
- * {@link DitherMethod}. Default: `'floyd-steinberg'`, like {@link GIFEncodeOptions.dither}
107
- */
108
- dither?: DitherMethod;
109
- /**
110
- * How strongly to apply dithering: `0` disables it; `1` applies it fully. Default: `0.85`, like
111
- * {@link GIFEncodeOptions.ditherStrength}
111
+ * color by its red, green and blue values; transparency in palette colors is ignored
112
112
  */
113
- ditherStrength?: number;
114
- }
113
+ palette: Color[];
114
+ /** Not with `palette`: give one of them */
115
+ colors?: never;
116
+ });
117
+ /** The directions of {@link Image.flip} and {@link Animation.flip}: `'horizontal'` mirrors left and right, `'vertical'` top and bottom */
118
+ export type FlipDirection = 'horizontal' | 'vertical';
115
119
  /** How {@link Image.transform} and {@link Image.rotate} sample the pixels between the source's */
116
120
  export type TransformMode = 'nearest-neighbor' | 'bilinear' | 'bicubic';
117
121
  /** The six values `[a, b, c, d, e, f]` of an affine transform */
@@ -219,23 +223,20 @@ export interface PNGEncodeOptions extends EncodeOptions {
219
223
  /** The compression level (0-9), higher is smaller but slower. Default: `4` */
220
224
  compression?: number;
221
225
  }
222
- /** Options of {@link Image.encodeTGA} */
223
- export type TGAEncodeOptions = EncodeOptions;
226
+ /** Options of {@link Image.encodeTGA}: the metadata, which TGA keeps in its extension area */
227
+ export interface TGAEncodeOptions extends EncodeOptions {
228
+ }
224
229
  /** Options of {@link Image.encodeGIF}, and of {@link Animation.encodeGIF} with {@link GIFAnimationEncodeOptions} */
225
- export interface GIFEncodeOptions extends EncodeOptions {
230
+ export interface GIFEncodeOptions extends EncodeOptions, DitherOptions {
226
231
  /**
227
232
  * The maximum colors in each frame's palette (2-256, including transparency). Frames with fewer colors keep them
228
233
  * exactly; otherwise ImageScript chooses representative colors. Default: `256`
229
234
  */
230
235
  colors?: number;
231
- /** How the rounding error is spread when the colors don't fit the palette, see {@link DitherMethod}. Default: `'floyd-steinberg'` */
232
- dither?: DitherMethod;
233
- /** How strongly to dither, from `0` (like `'none'`) to `1` (the full error). Default: `0.85` */
234
- ditherStrength?: number;
235
236
  }
236
237
  /** Options of {@link Image.encodeJPEG} */
237
238
  export interface JPEGEncodeOptions extends EncodeOptions {
238
- /** The JPEG quality (1-100). Default: `90` */
239
+ /** The JPEG quality (0-100, 0 is the same as 1). Default: `90` */
239
240
  quality?: number;
240
241
  /**
241
242
  * How much color detail to keep: `'4:4:4'` keeps it all; `'4:2:0'` stores less color detail to make a smaller
@@ -292,24 +293,12 @@ export interface FisheyeOptions {
292
293
  /** The distortion strength (exponent of the radial mapping), higher values bulge the center more. Default: `2` */
293
294
  strength?: number;
294
295
  }
295
- /** Options of {@link Image.renderSVG} */
296
- export interface RenderSVGOptions {
297
- /**
298
- * The width in pixels, the height follows the SVG's aspect ratio. Give one of `width`, `height` and `scale`.
299
- * Default: the SVG's own width
300
- */
301
- width?: number;
302
- /** The height in pixels, the width follows the SVG's aspect ratio. Give one of `width`, `height` and `scale` */
303
- height?: number;
304
- /**
305
- * A factor of the SVG's own size (`2` renders it twice as large). Give one of `width`, `height` and `scale`.
306
- * Default: `1`
307
- */
308
- scale?: number;
296
+ /** The limits, fonts and images of {@link Image.renderSVG}, part of {@link RenderSVGOptions} */
297
+ export interface SVGResourceOptions {
309
298
  /**
310
299
  * Maximum total pixels in the rendered output. Output over the limit throws a RangeError before anything is
311
- * rendered. It's also the default of {@link RenderSVGOptions.maxLayerPixels} and
312
- * {@link RenderSVGOptions.maxImagePixels}. Default: `268402689` (16383²); `Infinity` disables the limit
300
+ * rendered. It's also the default of {@link SVGResourceOptions.maxLayerPixels} and
301
+ * {@link SVGResourceOptions.maxImagePixels}. Default: `268402689` (16383²); `Infinity` disables the limit
313
302
  */
314
303
  maxPixels?: number;
315
304
  /**
@@ -322,7 +311,7 @@ export interface RenderSVGOptions {
322
311
  */
323
312
  maxLayerPixels?: number;
324
313
  /**
325
- * Maximum total pixels of the raster images the SVG references (data URIs and {@link RenderSVGOptions.images}),
314
+ * Maximum total pixels of the raster images the SVG references (data URIs and {@link SVGResourceOptions.images}),
326
315
  * decoded together; already-decoded {@link Image} values are used as supplied and don't count. Drawing an image
327
316
  * beyond the limit throws a RangeError. Default: `maxPixels`; `Infinity` disables the limit
328
317
  */
@@ -337,7 +326,7 @@ export interface RenderSVGOptions {
337
326
  * before these for their family names. Without any fonts text isn't rendered. One font can be given without an
338
327
  * array. Default: `[]`
339
328
  */
340
- fonts?: BinaryData | BinaryData[];
329
+ font?: BinaryData | BinaryData[];
341
330
  /**
342
331
  * Images for the `<image>` elements (and `feImage`) by their `href`, the same string the SVG uses: with
343
332
  * `images: { 'logo.png': bytes }`, `<image href="logo.png" .../>` draws the image. Values are encoded images (PNG,
@@ -348,6 +337,32 @@ export interface RenderSVGOptions {
348
337
  */
349
338
  images?: Record<string, BinaryData | Image>;
350
339
  }
340
+ /**
341
+ * Options of {@link Image.renderSVG}: the size (one of `width`, `height` and `scale`, TypeScript reports a call with
342
+ * more; by default the SVG's own size), and the limits, fonts and images (see {@link SVGResourceOptions})
343
+ */
344
+ export type RenderSVGOptions = SVGResourceOptions & ({
345
+ /** The width in pixels, the height follows the SVG's aspect ratio. Default: the SVG's own width */
346
+ width?: number;
347
+ /** Not with `width`: give one of `width`, `height` and `scale` */
348
+ height?: never;
349
+ /** Not with `width`: give one of `width`, `height` and `scale` */
350
+ scale?: never;
351
+ } | {
352
+ /** Not with `height`: give one of `width`, `height` and `scale` */
353
+ width?: never;
354
+ /** The height in pixels, the width follows the SVG's aspect ratio */
355
+ height: number;
356
+ /** Not with `height`: give one of `width`, `height` and `scale` */
357
+ scale?: never;
358
+ } | {
359
+ /** Not with `scale`: give one of `width`, `height` and `scale` */
360
+ width?: never;
361
+ /** Not with `scale`: give one of `width`, `height` and `scale` */
362
+ height?: never;
363
+ /** A factor of the SVG's own size (`2` renders it twice as large). Default: `1` */
364
+ scale: number;
365
+ });
351
366
  /**
352
367
  * Options of {@link Image.renderText}: the font and size, the text color, the layout (wrapping, cutting off and alignment,
353
368
  * see {@link TextLayoutOptions}) and the style (see {@link TextStyleOptions})
@@ -503,11 +518,11 @@ export interface CropCircleOptions {
503
518
  }
504
519
  /** Options of {@link Image.dominantColor} */
505
520
  export interface DominantColorOptions {
506
- /** Whether to ignore dark colors (all channels below the threshold). Default: `true` */
521
+ /** Whether to ignore dark colors (all channels below `threshold`). Default: `true` */
507
522
  ignoreBlack?: boolean;
508
- /** Whether to ignore light colors (all channels above 255 minus the threshold). Default: `true` */
523
+ /** Whether to ignore light colors (all channels above 255 minus `threshold`). Default: `true` */
509
524
  ignoreWhite?: boolean;
510
- /** The black/white threshold (0-64, in steps of 4 channel values). Default: `15` */
525
+ /** How close (in channel values, 0-256) to black or white a color has to be to be ignored. Default: `60` */
511
526
  threshold?: number;
512
527
  }
513
528
  /** Options of {@link Image.rotate} */
@@ -590,11 +605,6 @@ export declare class Image {
590
605
  * The image's height
591
606
  */
592
607
  get height(): number;
593
- /**
594
- * Yields an [x, y] array for every pixel in the image (0-based), row by row
595
- * @yields The coordinates of the pixel ([x, y])
596
- */
597
- coordinates(): Generator<[x: number, y: number], void, undefined>;
598
608
  /**
599
609
  * Yields an [x, y, color] array for every pixel in the image (0-based), row by row
600
610
  * @yields The coordinates and color of the pixel ([x, y, color])
@@ -706,9 +716,9 @@ export declare class Image {
706
716
  recolor(colors: Image): this;
707
717
  /**
708
718
  * Scales the opacity of the image
709
- * @param opacity The factor to multiply the opacity with (0..1 lowers it, >1 raises it, results are clamped)
719
+ * @param factor The factor to multiply the opacity with (0..1 lowers it, >1 raises it, results are clamped)
710
720
  */
711
- opacity(opacity: number): this;
721
+ opacity(factor: number): this;
712
722
  /**
713
723
  * Scales the red channel
714
724
  * @param factor The factor to multiply the channel with (>= 0, results are clamped)
@@ -861,8 +871,8 @@ export declare class Image {
861
871
  */
862
872
  averageColor(): Color;
863
873
  /**
864
- * Gets the image's dominant color: the colors are grouped into a few clusters (median cut and k-means),
865
- * the average color of the largest one is returned
874
+ * Gets the image's dominant color: the colors are counted in a histogram of 16 levels per channel, and the average
875
+ * of the pixels in the fullest bin is returned (so it is a color the image has, not a mix of two hues)
866
876
  * @param options Which colors to ignore, see {@link DominantColorOptions}
867
877
  * @return The image's dominant color (fully opaque); mostly transparent pixels are ignored.
868
878
  * If every pixel is ignored as black or white, the filter is dropped
@@ -871,16 +881,17 @@ export declare class Image {
871
881
  /**
872
882
  * Rotates the image clockwise by the given angle in degrees (like CSS' `rotate()`; negative angles turn it
873
883
  * counterclockwise). Multiples of 90° move whole pixels; other angles resample the image (see
874
- * {@link RotateOptions.mode}) and, by default, grow it so the corners fit
884
+ * {@link RotateOptions.mode}). By default the image grows so the corners fit (a quarter turn swaps width and
885
+ * height); with `expand: false` it keeps its size, also for quarter turns, and what doesn't fit is cut off
875
886
  * @param angle The angle in degrees, clockwise
876
887
  * @param options See {@link RotateOptions}
877
888
  */
878
889
  rotate(angle: number, options?: RotateOptions): this;
879
890
  /**
880
891
  * Flips / mirrors the image horizontally or vertically
881
- * @param direction The direction to flip
892
+ * @param direction The direction to flip, see {@link FlipDirection}
882
893
  */
883
- flip(direction: 'horizontal' | 'vertical'): this;
894
+ flip(direction: FlipDirection): this;
884
895
  /**
885
896
  * Rounds the image's corners, with antialiased edges
886
897
  * @param options See {@link RoundCornersOptions}
@@ -967,8 +978,8 @@ export declare class Image {
967
978
  * Creates a new image from the given SVG.
968
979
  * Supports shapes, paths, transforms, use/symbol, CSS styles, gradients, patterns, strokes, markers, clip paths,
969
980
  * masks, opacity, blend modes, filters (all primitives and the filter functions) and images embedded as data URIs
970
- * (PNG, JPEG, GIF, WebP, SVG) or given with {@link RenderSVGOptions.images}, and text with the given or embedded fonts
971
- * (see {@link RenderSVGOptions.fonts}). Hrefs are resolved from the options and the data URIs only, never from files or URLs:
981
+ * (PNG, JPEG, GIF, WebP, SVG) or given with {@link SVGResourceOptions.images}, and text with the given or embedded fonts
982
+ * (see {@link SVGResourceOptions.font}). Hrefs are resolved from the options and the data URIs only, never from files or URLs:
972
983
  * drawing an image that isn't given, or can't be decoded, throws.
973
984
  * @example
974
985
  * ```ts
@@ -985,8 +996,8 @@ export declare class Image {
985
996
  /**
986
997
  * Creates a new image containing the rendered text.
987
998
  * @param text Text to render
988
- * @param options The font and size, color, layout and style, see {@link RenderTextOptions}; the image grows by the
989
- * outline width on every side
999
+ * @param options The font and size, color, layout and style, see {@link RenderTextOptions}. Without a `width` or
1000
+ * `height`, the image grows by the outline width on every side; with one, it has exactly that size
990
1001
  * @return The rendered text
991
1002
  */
992
1003
  static renderText(text: string, options: RenderTextOptions): Promise<Image>;
package/dist/image.js CHANGED
@@ -13,10 +13,6 @@ import * as avif from "./codecs/avif.js";
13
13
  import * as avifEnc from "./codecs/avif-enc.js";
14
14
  import { availableThreads } from "./util/threads.js";
15
15
  const defaultThreads = () => Math.max(1, Math.min(availableThreads(), 8));
16
- const checkThreads = (threads) => {
17
- if (!Number.isInteger(threads) || threads < 1)
18
- throw new RangeError(`threads must be a positive integer, not ${threads}`);
19
- };
20
16
  import * as jxl from "./codecs/jxl.js";
21
17
  import * as quantize from "./codecs/quantize.js";
22
18
  import * as textRenderer from "./render/text.js";
@@ -24,13 +20,13 @@ import * as svgRenderer from "./render/svg.js";
24
20
  import { view } from "./util/mem.js";
25
21
  import { cicpTransform, colorSpaceTransform, profileTransform } from "./util/icc.js";
26
22
  import { ImageType } from "./image-type.js";
27
- import { TextLayout } from "./text-layout.js";
23
+ import { textLayout } from "./text-layout.js";
28
24
  import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
29
25
  import { encode as utf8 } from "./util/utf8.js";
30
26
  import { resample, BOX, TRIANGLE, CUBIC } from "./util/resample.js";
31
27
  import { gaussianBlur, boxBlurRGBA, premultiply, unpremultiply } from "./util/blur.js";
32
28
  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";
29
+ import { isOptions, checkOptions, finite, oneOf, pixelLimit, checkThreads, gainMapScale, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
34
30
  import { MAX_PIXELS, LimitError, decoding } from "./util/limits.js";
35
31
  import { GainMap } from "./gainmap.js";
36
32
  import * as gain from "./util/gain.js";
@@ -38,6 +34,10 @@ import { multiply, invert } from "./util/matrix.js";
38
34
  import { sampleAffine } from "./util/affine.js";
39
35
  import * as gainMapCodec from "./codecs/gainmap.js";
40
36
  const TRANSFORM_MODES = ['nearest-neighbor', 'bilinear', 'bicubic'];
37
+ const RESIZE_FITS = ['fill', 'inside', 'contain', 'cover'];
38
+ const SUBSAMPLINGS = ['4:4:4', '4:2:0'];
39
+ export const TONE_MAPPINGS = ['reinhard', 'clamp'];
40
+ export const FLIP_DIRECTIONS = ['horizontal', 'vertical'];
41
41
  function featureList(features) {
42
42
  if (typeof features !== 'object' || features === null)
43
43
  throw new TypeError('Features must be an object');
@@ -109,11 +109,6 @@ export class Image {
109
109
  get height() {
110
110
  return this.__height__;
111
111
  }
112
- *coordinates() {
113
- for (let y = 0; y < this.height; y++)
114
- for (let x = 0; x < this.width; x++)
115
- yield [x, y];
116
- }
117
112
  *pixels() {
118
113
  const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength);
119
114
  let offset = 0;
@@ -127,6 +122,7 @@ export class Image {
127
122
  const color = gradientFunction(stops);
128
123
  finite(angle, 'angle');
129
124
  const image = new Image(width, height);
125
+ ({ width, height } = image);
130
126
  const radians = angle * Math.PI / 180;
131
127
  const dx = Math.sin(radians), dy = -Math.cos(radians);
132
128
  const length = Math.abs(width * dx) + Math.abs(height * dy);
@@ -138,13 +134,14 @@ export class Image {
138
134
  }
139
135
  static radialGradient(width, height, options) {
140
136
  checkOptions(options, 'Image.radialGradient(100, 50, { stops })');
137
+ const image = new Image(width, height);
138
+ ({ width, height } = image);
141
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;
142
140
  const color = gradientFunction(stops);
143
141
  finite(cx, 'x');
144
142
  finite(cy, 'y');
145
143
  if (!(finite(radius, 'radius') > 0))
146
144
  throw new RangeError('Invalid radius');
147
- const image = new Image(width, height);
148
145
  const bitmap = new DataView(image.bitmap.buffer, image.bitmap.byteOffset, image.bitmap.byteLength);
149
146
  for (let y = 0, i = 0; y < height; y++)
150
147
  for (let x = 0; x < width; x++, i += 4)
@@ -213,16 +210,17 @@ export class Image {
213
210
  }
214
211
  scale(factor, options) {
215
212
  checkOptions(options, 'scale(factor, { mode: \'area\' })');
216
- const { mode, fast } = resizeOptions(options);
217
- const image = this.__scale__(factor, mode, fast);
213
+ const { mode } = resizeOptions(options);
214
+ const image = this.__scale__(factor, mode);
218
215
  this.__gain_map__?.__rescale__(this.width, this.height, image.width, image.height);
219
216
  this.__moved__?.(image.width / this.width, image.height / this.height, 0, 0);
220
217
  return this.__apply__(image);
221
218
  }
222
- __scale__(factor, mode = 'bilinear', fast = true) {
219
+ __scale__(factor, mode = 'bilinear') {
223
220
  if (factor === 1)
224
221
  return this;
225
- return this.__resize__(this.width * factor, this.height * factor, mode, fast);
222
+ const size = (side) => factor > 0 ? Math.max(1, side * factor) : side * factor;
223
+ return this.__resize__(size(this.width), size(this.height), mode);
226
224
  }
227
225
  resize(widthOrOptions, heightArgument, optionsArgument) {
228
226
  const [width, height, options, fit] = resizeArguments(widthOrOptions, heightArgument, optionsArgument);
@@ -233,8 +231,8 @@ export class Image {
233
231
  ? this.__contain__(width, height, options)
234
232
  : this.__cover__(width, height, options);
235
233
  }
236
- const { mode, fast } = resizeOptions(options);
237
- const image = this.__resize__(...this.__resized_size__(width, height, fit), mode, fast);
234
+ const { mode } = resizeOptions(options);
235
+ const image = this.__resize__(...this.__resized_size__(width, height, fit), mode);
238
236
  this.__gain_map__?.__rescale__(this.width, this.height, image.width, image.height);
239
237
  this.__moved__?.(image.width / this.width, image.height / this.height, 0, 0);
240
238
  return this.__apply__(image);
@@ -274,7 +272,7 @@ export class Image {
274
272
  const fx = resizedWidth / this.width, fy = resizedHeight / this.height;
275
273
  this.__gain_map__?.__transform__(this.width, this.height, width, height, (X, Y) => [(X + region.x) / fx, (Y + region.y) / fy], Math.min(fx, fy));
276
274
  this.__moved__?.(fx, fy, region.x, region.y);
277
- return this.__apply__(this.__resize__(resizedWidth, resizedHeight, resizeOpts.mode, resizeOpts.fast, region));
275
+ return this.__apply__(this.__resize__(resizedWidth, resizedHeight, resizeOpts.mode, region));
278
276
  }
279
277
  this.resize(resizedWidth, resizedHeight, resizeOpts);
280
278
  return this.crop((this.width - width) / 2, (this.height - height) / 2, width, height);
@@ -288,7 +286,7 @@ export class Image {
288
286
  return [width, Math.max(1, Math.round(this.height / this.width * Math.floor(width)))];
289
287
  return [width, height];
290
288
  }
291
- __resize__(width, height, mode = 'bilinear', fast = true, region) {
289
+ __resize__(width, height, mode = 'bilinear', region) {
292
290
  width = Math.floor(width);
293
291
  height = Math.floor(height);
294
292
  if (width < 1)
@@ -300,7 +298,7 @@ export class Image {
300
298
  return this.__resize_nearest_neighbor__(width, height);
301
299
  const filter = mode === 'bilinear' ? TRIANGLE : mode === 'bicubic' ? CUBIC : BOX;
302
300
  const image = new Image(region?.width ?? width, region?.height ?? height);
303
- resample(this.bitmap, this.width, this.height, width, height, filter, image.bitmap, fast, region);
301
+ resample(this.bitmap, this.width, this.height, width, height, filter, image.bitmap, true, region);
304
302
  return image;
305
303
  }
306
304
  __resize_nearest_neighbor__(width, height) {
@@ -458,11 +456,11 @@ export class Image {
458
456
  }
459
457
  return this;
460
458
  }
461
- opacity(opacity) {
462
- opacity = finite(opacity, 'opacity value');
463
- if (opacity < 0)
459
+ opacity(factor) {
460
+ factor = finite(factor, 'opacity value');
461
+ if (factor < 0)
464
462
  throw new RangeError('Invalid opacity value');
465
- this.__set_channel_value__(opacity, 3);
463
+ this.__set_channel_value__(factor, 3);
466
464
  return this;
467
465
  }
468
466
  red(factor) {
@@ -514,6 +512,8 @@ export class Image {
514
512
  }
515
513
  composite(source, options = {}) {
516
514
  checkOptions(options, 'composite(source, { x: 10, y: 20 })');
515
+ if (!(source instanceof Image))
516
+ throw new TypeError('composite() takes an Image as its source, like image.composite(logo, { x: 10, y: 20 })');
517
517
  const { opacity = 1, mode = 'normal' } = options;
518
518
  let x = options.x ?? 0, y = options.y ?? 0;
519
519
  x = Math.trunc(finite(x, 'x'));
@@ -745,8 +745,6 @@ export class Image {
745
745
  }
746
746
  quantize(options = {}) {
747
747
  checkOptions(options, 'image.quantize({ colors: 16 })');
748
- if (typeof options !== 'object' || options === null)
749
- throw new TypeError('quantize takes an options object');
750
748
  const { colors, palette, dither = 'floyd-steinberg', ditherStrength = 0.85 } = options;
751
749
  if (colors !== undefined && palette !== undefined)
752
750
  throw new TypeError('quantize takes colors or palette, not both');
@@ -812,11 +810,8 @@ export class Image {
812
810
  if (matrix === null || typeof matrix !== 'object' || matrix.length !== 6)
813
811
  throw new RangeError('A transform has 6 values: [a, b, c, d, e, f]');
814
812
  const values = Array.from({ length: 6 }, (_, i) => finite(typeof matrix[i] === 'number' ? matrix[i] : NaN, 'transform value'));
815
- if (typeof options !== 'object' || options === null)
816
- throw new TypeError('transform takes an options object');
817
813
  const { origin = {}, expand = true, mode = 'bilinear' } = options;
818
- if (!TRANSFORM_MODES.includes(mode))
819
- throw new TypeError(`transform mode must be one of ${TRANSFORM_MODES.map(name => `'${name}'`).join(', ')}, not ${String(mode)}`);
814
+ oneOf(mode, TRANSFORM_MODES, 'transform mode');
820
815
  const { x: pivotX = this.width / 2, y: pivotY = this.height / 2 } = origin;
821
816
  finite(pivotX, 'origin x');
822
817
  finite(pivotY, 'origin y');
@@ -1060,8 +1055,8 @@ export class Image {
1060
1055
  }
1061
1056
  dominantColor(options = {}) {
1062
1057
  checkOptions(options, 'dominantColor({ ignoreBlack: false })');
1063
- const { ignoreBlack = true, ignoreWhite = true, threshold: bwThreshold = 0xf } = options;
1064
- const threshold = Math.min(64, Math.max(0, finite(bwThreshold, 'threshold'))) * 4;
1058
+ const { ignoreBlack = true, ignoreWhite = true, threshold: bwThreshold = 60 } = options;
1059
+ const threshold = Math.min(256, Math.max(0, finite(bwThreshold, 'threshold')));
1065
1060
  const pixels = this.__bytes__();
1066
1061
  const color = quantize.dominantColor(pixels, (r, g, b) => !(ignoreBlack && Math.max(r, g, b) < threshold) && !(ignoreWhite && Math.min(r, g, b) > 255 - threshold))
1067
1062
  || quantize.dominantColor(pixels, () => true);
@@ -1070,8 +1065,7 @@ export class Image {
1070
1065
  rotate(angle, options = {}) {
1071
1066
  checkOptions(options, 'rotate(angle, { expand: false })');
1072
1067
  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)}`);
1068
+ oneOf(mode, TRANSFORM_MODES, 'rotate mode');
1075
1069
  angle = ((-finite(angle, 'angle') % 360) + 360) % 360;
1076
1070
  if (angle === 0)
1077
1071
  return this;
@@ -1097,6 +1091,16 @@ export class Image {
1097
1091
  else
1098
1092
  dst[x * height + height - 1 - y] = i;
1099
1093
  }
1094
+ if (!expand && out.width !== width) {
1095
+ const canvas = new Image(width, height), target = canvas.__u32__, turned = out.__u32__;
1096
+ const left = Math.floor((width - out.width) / 2), top = Math.floor((height - out.height) / 2);
1097
+ for (let y = Math.max(0, top); y < Math.min(height, top + out.height); y++)
1098
+ for (let x = Math.max(0, left); x < Math.min(width, left + out.width); x++)
1099
+ target[y * width + x] = turned[(y - top) * out.width + x - left];
1100
+ rotateGainMap(width, height);
1101
+ this.__moved__?.(1, 1, 0, 0);
1102
+ return this.__apply__(canvas);
1103
+ }
1100
1104
  rotateGainMap(out.width, out.height);
1101
1105
  this.__moved__?.(1, 1, (width - out.width) / 2, (height - out.height) / 2);
1102
1106
  return this.__apply__(out);
@@ -1114,7 +1118,7 @@ export class Image {
1114
1118
  return this.__apply__(out);
1115
1119
  }
1116
1120
  flip(direction) {
1117
- oneOf(direction, ['horizontal', 'vertical'], 'flip direction');
1121
+ oneOf(direction, FLIP_DIRECTIONS, 'flip direction');
1118
1122
  const u32 = this.__u32__;
1119
1123
  const { width, height } = this;
1120
1124
  if (direction === 'horizontal') {
@@ -1229,28 +1233,27 @@ export class Image {
1229
1233
  }
1230
1234
  async encodeJPEG(options = {}) {
1231
1235
  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)}`);
1236
+ const { quality: qualityOption = 90, subsampling, background = 0x000000ff, metadata = {}, gainMap: gainMapOption = true } = options;
1237
+ const quality = checkQuality(qualityOption);
1238
+ if (subsampling !== undefined)
1239
+ oneOf(subsampling, SUBSAMPLINGS, 'subsampling');
1235
1240
  const backgroundColor = checkColor(background, 'background');
1236
1241
  const m = resolveMetadata(metadata);
1237
1242
  const base = { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined, subsampling };
1238
1243
  const source = this.__flattened__(backgroundColor, gainMapOption !== false) ?? this;
1239
1244
  const gainMap = source.__gain_map__;
1240
1245
  if (!gainMap || gainMapOption === false)
1241
- return jpeg.encode(source.__bytes__(), source.width, source.height, finite(quality, 'quality'), base);
1246
+ return jpeg.encode(source.__bytes__(), source.width, source.height, quality, base);
1242
1247
  const { quality: mapQuality, scale } = typeof gainMapOption === 'object' && gainMapOption !== null ? gainMapOption : {};
1243
1248
  let width, height;
1244
1249
  if (scale !== undefined) {
1245
- const s = finite(scale, 'gain map scale');
1246
- if (!(s > 0 && s <= 1))
1247
- throw new RangeError(`The gain map scale must be above 0 and at most 1, not ${s}`);
1250
+ const s = gainMapScale(scale);
1248
1251
  width = Math.max(1, Math.round(this.width * s));
1249
1252
  height = Math.max(1, Math.round(this.height * s));
1250
1253
  }
1251
1254
  const params = gainMap.__params__();
1252
1255
  const map = gainMapCodec.mapWithMetadata(gainMap.__body__(mapQuality === undefined ? undefined : Math.max(1, checkQuality(mapQuality, 'gain map quality')), width, height), params);
1253
- const primary = jpeg.encode(source.__bytes__(), source.width, source.height, finite(quality, 'quality'), { ...base, segments: gainMapCodec.primarySegments(map.length) });
1256
+ const primary = jpeg.encode(source.__bytes__(), source.width, source.height, quality, { ...base, segments: gainMapCodec.primarySegments(map.length) });
1254
1257
  return gainMapCodec.finish(primary, map);
1255
1258
  }
1256
1259
  __flattened__(background, withGainMap) {
@@ -1303,8 +1306,7 @@ export class Image {
1303
1306
  const { quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true } = options;
1304
1307
  checkEffort(effort, 2);
1305
1308
  checkThreads(threads);
1306
- if (subsampling !== '4:4:4' && subsampling !== '4:2:0')
1307
- throw new TypeError(`subsampling must be '4:4:4' or '4:2:0', not ${String(subsampling)}`);
1309
+ oneOf(subsampling, SUBSAMPLINGS, 'subsampling');
1308
1310
  const exif = exifData(resolveMetadata(metadata));
1309
1311
  return avifEnc.encode(this.__bytes__(), this.width, this.height, {
1310
1312
  quality: checkQuality(quality), alphaQuality: checkQuality(alphaQuality, 'alphaQuality'), subsampling, effort, exif, threads, gainMap: this.__gain_map_pixels__(gainMap)
@@ -1318,9 +1320,7 @@ export class Image {
1318
1320
  const mapQuality = Math.max(1, checkQuality(quality, 'gain map quality'));
1319
1321
  let map = gainMap.image;
1320
1322
  if (scale !== undefined) {
1321
- const s = finite(scale, 'gain map scale');
1322
- if (!(s > 0 && s <= 1))
1323
- throw new RangeError(`The gain map scale must be above 0 and at most 1, not ${s}`);
1323
+ const s = gainMapScale(scale);
1324
1324
  const width = Math.max(1, Math.round(this.width * s)), height = Math.max(1, Math.round(this.height * s));
1325
1325
  if (width !== map.width || height !== map.height)
1326
1326
  map = map.clone().resize(width, height);
@@ -1344,10 +1344,8 @@ export class Image {
1344
1344
  checkOptions(options, 'Image.decode(data, { maxPixels: 1e8 })');
1345
1345
  const { applyOrientation = true, applyColorProfile = true, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = defaultThreads(), gainMap = true } = options;
1346
1346
  checkThreads(threads);
1347
- if (!(Number(maxPixels) > 0))
1348
- throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
1349
- if (toneMapping !== 'reinhard' && toneMapping !== 'clamp')
1350
- throw new TypeError(`toneMapping must be 'reinhard' or 'clamp', not ${String(toneMapping)}`);
1347
+ pixelLimit(maxPixels);
1348
+ oneOf(toneMapping, TONE_MAPPINGS, 'toneMapping');
1351
1349
  const data = view(input);
1352
1350
  const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
1353
1351
  const decoded = await decoding(() => {
@@ -1405,7 +1403,7 @@ export class Image {
1405
1403
  const found = gainMapCodec.find(data);
1406
1404
  const size = found && gainMapCodec.dimensions(found.map);
1407
1405
  if (found && size && size.width * size.height <= maxPixels)
1408
- image.__gain_map__ = GainMap.__from_jpeg__(found.map, found.params, found.apple);
1406
+ image.__gain_map__ = GainMap.__from_jpeg__(found.map, found.params, found.apple, maxPixels);
1409
1407
  }
1410
1408
  catch {
1411
1409
  image.__gain_map__ = null;
@@ -1479,14 +1477,11 @@ export class Image {
1479
1477
  }
1480
1478
  static async renderSVG(svg, options = {}) {
1481
1479
  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}`);
1480
+ const { width: givenWidth, height: givenHeight, scale, maxPixels = MAX_PIXELS, font: fonts = [], images: givenImages = {} } = options;
1481
+ pixelLimit(maxPixels);
1485
1482
  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}`);
1483
+ pixelLimit(maxLayerPixels, 'maxLayerPixels');
1484
+ pixelLimit(maxImagePixels, 'maxImagePixels');
1490
1485
  const sizes = [givenWidth, givenHeight, scale].filter(value => value !== undefined).length;
1491
1486
  if (sizes > 1)
1492
1487
  throw new TypeError('renderSVG() takes one of width, height and scale');
@@ -1550,10 +1545,9 @@ export class Image {
1550
1545
  if (options.font === undefined)
1551
1546
  throw new TypeError('renderText(text, options) needs the font in the options');
1552
1547
  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 });
1548
+ pixelLimit(maxPixels);
1549
+ const { width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign } = options;
1550
+ const layout = textLayout({ width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign });
1557
1551
  const axes = textRenderer.axisValues(variations);
1558
1552
  const size = finite(options.size, 'font size');
1559
1553
  if (size < 0)
@@ -1565,6 +1559,14 @@ export class Image {
1565
1559
  throw new RangeError('No font given');
1566
1560
  const [r, g, b, a] = Colors.toRGBA(color);
1567
1561
  const pad = Math.ceil(strokeWidth);
1562
+ if (layout.width !== undefined && layout.width <= 2 * pad)
1563
+ throw new RangeError(`The width (${layout.width}) leaves no room for the text inside the ${strokeWidth} pixel outline`);
1564
+ if (layout.height !== undefined && layout.height <= 2 * pad)
1565
+ throw new RangeError(`The height (${layout.height}) leaves no room for the text inside the ${strokeWidth} pixel outline`);
1566
+ if (layout.width !== undefined)
1567
+ layout.width -= 2 * pad;
1568
+ if (layout.height !== undefined)
1569
+ layout.height -= 2 * pad;
1568
1570
  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);
1569
1571
  const width = rendered.width + 2 * pad, height = rendered.height + 2 * pad;
1570
1572
  const coverage = new Uint8Array(width * height);
@@ -1650,8 +1652,7 @@ export function resizeArguments(widthOrOptions, height, options) {
1650
1652
  const { width, height: optionsHeight, fit = 'fill', ...rest } = widthOrOptions;
1651
1653
  if (width === undefined && optionsHeight === undefined)
1652
1654
  throw new TypeError('resize() needs a width, a height or both');
1653
- if (!['fill', 'inside', 'contain', 'cover'].includes(fit))
1654
- throw new TypeError(`fit must be 'fill', 'inside', 'contain' or 'cover', not ${String(fit)}`);
1655
+ oneOf(fit, RESIZE_FITS, 'fit');
1655
1656
  return [width === undefined ? undefined : finite(width, 'width'), optionsHeight === undefined ? undefined : finite(optionsHeight, 'height'), rest, fit];
1656
1657
  }
1657
1658
  export function insideSize(width, height, boxWidth, boxHeight) {
@@ -1662,7 +1663,7 @@ export function insideSize(width, height, boxWidth, boxHeight) {
1662
1663
  }
1663
1664
  const RESIZE_MODES = ['nearest-neighbor', 'bilinear', 'bicubic', 'area'];
1664
1665
  function resizeOptions(options) {
1665
- return { mode: options?.mode === undefined ? 'bilinear' : oneOf(options.mode, RESIZE_MODES, 'resize mode'), fast: options?.fast ?? true };
1666
+ return { mode: options?.mode === undefined ? 'bilinear' : oneOf(options.mode, RESIZE_MODES, 'resize mode') };
1666
1667
  }
1667
1668
  const hardLight = (b, s) => s <= 0.5 ? b * 2 * s : 1 - (1 - b) * (1 - (2 * s - 1));
1668
1669
  const BLEND_MODES = {