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/README.md CHANGED
@@ -13,21 +13,24 @@
13
13
 
14
14
  ---
15
15
 
16
- **ImageScript** decodes, edits and encodes images in pure TypeScript: no WebAssembly, no native binaries, no
17
- dependencies. It runs in Node.js 22.13+, Deno, Bun, browsers and edge runtimes (Cloudflare Workers, Vercel's Edge
18
- Runtime, Deno Deploy), works with both `import` and `require()`, and ships with type definitions. Large images are
19
- encoded and decoded on several threads wherever the runtime supports workers.
16
+ **ImageScript** decodes, edits and encodes images in pure TypeScript: no WebAssembly, no native binaries, and no
17
+ runtime dependencies. It runs in Node.js 22.13+, Deno, Bun, browsers and edge runtimes (Cloudflare Workers, Vercel's
18
+ Edge Runtime, Deno Deploy), works with `import` and, on supported Node.js versions, `require()`, and ships with type
19
+ definitions. Large AVIF and JPEG XL operations, and lossless WebP encoding, can use multiple CPU cores when the runtime
20
+ supports it.
20
21
 
21
22
  ```sh
22
23
  npm install imagescript # Node.js, Bun and bundlers
23
24
  deno add jsr:@matmen/imagescript # Deno
24
25
  ```
25
26
 
27
+ Upgrading from 3.x? Read [Migrating to 4.0](https://imagescript.dev/documents/Migrating_to_4.0.html) first.
28
+
26
29
  Without a bundler, import it from jsDelivr in the browser:
27
30
 
28
31
  ```html
29
32
  <script type="module">
30
- import { Image } from 'https://cdn.jsdelivr.net/npm/imagescript@3/+esm';
33
+ import { Image } from 'https://cdn.jsdelivr.net/npm/imagescript@4/+esm';
31
34
 
32
35
  const image = await Image.decode(await fetch('photo.jpg').then(r => r.arrayBuffer()));
33
36
  image.resize({ width: 256 });
@@ -45,7 +48,7 @@ import { Image } from 'imagescript';
45
48
  import { readFile, writeFile } from 'node:fs/promises';
46
49
 
47
50
  const image = await Image.decode(await readFile('input.jpg'));
48
- image.resize({ width: 256 }).roundCorners(16);
51
+ image.resize({ width: 256 }).roundCorners({ radius: 16 });
49
52
  await writeFile('output.png', await image.encodePNG());
50
53
  ```
51
54
 
@@ -71,17 +74,23 @@ await writeFile('output.png', await image.encodePNG());
71
74
  | GIF, APNG (animations) | ✓ | ✓ |
72
75
  | BMP, QOI, TGA, Netpbm | ✓ | ✓ |
73
76
  | TIFF, ICO/CUR, Radiance HDR | ✓ | |
74
- | [HDR gain maps](https://imagescript.dev/classes/GainMap.html) (Ultra HDR and iPhone JPEGs, AVIF, JPEG XL) | ✓ | ✓, kept through edits |
77
+ | [HDR gain maps](https://imagescript.dev/classes/GainMap.html) (brighter highlights on HDR displays; JPEG, AVIF, JPEG XL) | ✓ | ✓ |
75
78
 
76
79
  [Animations](https://imagescript.dev/classes/Animation.html) can be decoded from GIF, APNG, WebP and JPEG XL,
77
80
  and encoded as GIF, APNG or WebP, all at once or
78
- [frame by frame](https://imagescript.dev/classes/Animation.html#webpencoder). Embedded color profiles (Display
79
- P3, Adobe RGB, ...) are converted to sRGB when decoding, so images look the way browsers show them.
81
+ [frame by frame](https://imagescript.dev/classes/Animation.html#webpencoder). Lossless encoding keeps every pixel
82
+ exactly; lossy encoding makes smaller files by approximating some image detail.
83
+
84
+ Embedded color profiles are converted to sRGB, the standard color format for most screens, where supported. CMYK and
85
+ lookup-table profiles are left unchanged.
86
+
87
+ Supported image operations preserve gain maps; editing pixels directly with `image.bitmap` or `setPixelAt()` does not.
80
88
 
81
- - [Text rendering](https://imagescript.dev/classes/Image.html#rendertext) with TrueType, OpenType and WOFF fonts:
82
- all scripts, color emoji, variable fonts
89
+ - [Text rendering](https://imagescript.dev/classes/Image.html#rendertext) with TrueType, OpenType and WOFF fonts
90
+ (not WOFF2; some OpenType outline formats are unsupported): right-to-left text and scripts where letters connect or
91
+ combine, plus color emoji and variable TrueType fonts
83
92
  - [SVG rendering](https://imagescript.dev/classes/Image.html#rendersvg), including text (with fonts you pass
84
- or fonts embedded in the SVG)
93
+ or fonts embedded in the SVG); no automatic fetching of external images or fonts
85
94
  - [Resizing](https://imagescript.dev/classes/Image.html#resize),
86
95
  [cropping](https://imagescript.dev/classes/Image.html#crop),
87
96
  [rotating](https://imagescript.dev/classes/Image.html#rotate),
@@ -1,32 +1,5 @@
1
1
  import { Image } from './image.js';
2
2
  import { Frame, FrameOptions } from './frame.js';
3
- import type { AnimationOptions, AnimationEncodeOptions, WebPAnimationEncodeOptions, GIFEncodeOptions, APNGEncodeOptions } from './animation.js';
4
- /**
5
- * The options all animation encoders of {@link Animation.webpEncoder} and the others have
6
- * @deprecated {@link Animation.webpEncoder} and the others take the options of {@link Animation.encodeWebP} and the
7
- * others ({@link AnimationEncodeOptions}) with the {@link AnimationOptions.loopCount}, this will be removed in 4.0
8
- * @group Deprecated
9
- */
10
- export type AnimationEncoderOptions = AnimationEncodeOptions & AnimationOptions;
11
- /**
12
- * Options of {@link Animation.webpEncoder}
13
- * @deprecated Use {@link WebPAnimationEncodeOptions}, with {@link AnimationOptions.loopCount}: this will be removed
14
- * in 4.0
15
- * @group Deprecated
16
- */
17
- export type WebPAnimationEncoderOptions = WebPAnimationEncodeOptions & AnimationOptions;
18
- /**
19
- * Options of {@link Animation.gifEncoder}
20
- * @deprecated Use {@link GIFEncodeOptions}, with {@link AnimationOptions.loopCount}: this will be removed in 4.0
21
- * @group Deprecated
22
- */
23
- export type GIFAnimationEncoderOptions = GIFEncodeOptions & AnimationOptions;
24
- /**
25
- * Options of {@link Animation.apngEncoder}
26
- * @deprecated Use {@link APNGEncodeOptions}, with {@link AnimationOptions.loopCount}: this will be removed in 4.0
27
- * @group Deprecated
28
- */
29
- export type APNGAnimationEncoderOptions = APNGEncodeOptions & AnimationOptions;
30
3
  /**
31
4
  * Encodes an animation a frame at a time, without keeping all frames in memory: see {@link Animation.webpEncoder},
32
5
  * {@link Animation.gifEncoder} and {@link Animation.apngEncoder}. The file is the one an {@link Animation} of the
@@ -47,12 +20,6 @@ export declare class AnimationEncoder {
47
20
  readonly height: number;
48
21
  /** How many frames were added */
49
22
  get frameCount(): number;
50
- /**
51
- * How many frames were added
52
- * @deprecated Use {@link AnimationEncoder.frameCount}, `frames` will be removed in 4.0
53
- * @group Deprecated
54
- */
55
- get frames(): number;
56
23
  /**
57
24
  * Adds the next frame: a {@link Frame} (with its duration, offsets and disposal) or an image (a frame of 100 ms by
58
25
  * default). The options override the frame's. The pixels are copied right away, the image can change afterwards
@@ -61,5 +28,5 @@ export declare class AnimationEncoder {
61
28
  */
62
29
  add(frame: Frame | Image, options?: FrameOptions): Promise<void>;
63
30
  /** Encodes the rest and returns the file. The encoder can't be used afterwards */
64
- finish(): Promise<Uint8Array>;
31
+ finish(): Promise<Uint8Array<ArrayBuffer>>;
65
32
  }
@@ -1,4 +1,5 @@
1
1
  import * as gifCodec from "./codecs/gif.js";
2
+ import { paletteOptions } from "./codecs/quantize.js";
2
3
  import * as png from "./codecs/png.js";
3
4
  import * as webp from "./codecs/webp.js";
4
5
  import { Image } from "./image.js";
@@ -6,8 +7,7 @@ import { Frame } from "./frame.js";
6
7
  import { Optimizer, Compositor, coverCanvas, fillUnchanged } from "./util/optimize.js";
7
8
  import { compressAsync, decompressAsync } from "./codecs/zlib.js";
8
9
  import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
9
- import { finite, compressionLevel } from "./util/options.js";
10
- const toPlays = (loopCount) => loopCount < 0 || loopCount === Infinity ? 0 : loopCount + 1;
10
+ import { checkOptions, finite, compressionLevel, loopCount, toPlays, fitLoops } from "./util/options.js";
11
11
  export class AnimationEncoder {
12
12
  format;
13
13
  optimizer;
@@ -25,15 +25,14 @@ export class AnimationEncoder {
25
25
  get frameCount() {
26
26
  return this.count;
27
27
  }
28
- get frames() {
29
- return this.count;
30
- }
31
28
  add(frame, options = {}) {
29
+ checkOptions(options, 'encoder.add(frame, { duration: 40 })');
32
30
  if (this.finished)
33
31
  throw new Error('The animation encoder is finished');
34
- if (!(frame instanceof Image))
35
- throw new TypeError('Invalid frame passed');
36
32
  const own = frame instanceof Frame ? frame : null;
33
+ const image = own ? own.image : frame;
34
+ if (!(image instanceof Image))
35
+ throw new TypeError('encoder.add() takes a Frame or an Image');
37
36
  const duration = options.duration ?? own?.duration ?? 100;
38
37
  const x = options.xOffset ?? own?.xOffset ?? 0, y = options.yOffset ?? own?.yOffset ?? 0;
39
38
  if (finite(duration, 'frame duration') < 0)
@@ -42,9 +41,9 @@ export class AnimationEncoder {
42
41
  finite(y, 'y offset');
43
42
  const disposal = options.disposalMode !== undefined ? Frame.__convert_disposal_mode__(options.disposalMode) : own ? own.__disposal_id__ : 1;
44
43
  const input = {
45
- x, y, width: frame.width, height: frame.height, duration, disposal,
44
+ x, y, width: image.width, height: image.height, duration, disposal,
46
45
  dispose: [0, 0, 2, 1][disposal],
47
- pixels: new Uint8Array(frame.bitmap.buffer, frame.bitmap.byteOffset, frame.bitmap.byteLength).slice()
46
+ pixels: new Uint8Array(image.bitmap.buffer, image.bitmap.byteOffset, image.bitmap.byteLength).slice()
48
47
  };
49
48
  this.count++;
50
49
  return this.queue = this.queue.then(async () => {
@@ -69,8 +68,9 @@ export class AnimationEncoder {
69
68
  this.optimizer = null;
70
69
  return this.format.file(optimizer);
71
70
  }
72
- static __webp__(width, height, { loopCount = -1, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 }) {
73
- canvas(width, height, loopCount);
71
+ static __webp__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 }) {
72
+ const loops = fitLoops(loopCount(count), 'WebP');
73
+ canvas(width, height);
74
74
  if (width > 1 << 24 || height > 1 << 24)
75
75
  throw new RangeError('WebP: canvas too large');
76
76
  const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
@@ -94,12 +94,14 @@ export class AnimationEncoder {
94
94
  return add({ x: 0, y: 0, width, height, duration: input.duration, dispose: true, blend: false, pixels: shown });
95
95
  await add(webpFrame(input));
96
96
  },
97
- file: () => webp.animationFile(chunks, width, height, toPlays(loopCount), alpha, exifData(resolved))
97
+ file: () => webp.animationFile(chunks, width, height, toPlays(loops), alpha, exifData(resolved))
98
98
  }, optimize);
99
99
  }
100
- static __gif__(width, height, { loopCount = -1, metadata = {}, optimize = true, quality: qualityOption = 95 }) {
101
- const quality = finite(qualityOption, 'quality');
102
- canvas(width, height, loopCount);
100
+ static __gif__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85 }) {
101
+ const checked = paletteOptions(colors, dither, ditherStrength);
102
+ const palette = { colors: checked.colors, dither: checked.dither, strength: checked.strength };
103
+ const loops = fitLoops(loopCount(count), 'GIF');
104
+ canvas(width, height);
103
105
  const comments = gifComments(resolveMetadata(metadata));
104
106
  let first = null, restores = false;
105
107
  const rest = [];
@@ -115,17 +117,18 @@ export class AnimationEncoder {
115
117
  if (!first)
116
118
  first = gif;
117
119
  else
118
- rest.push(gifCodec.encodeFrame(gif, quality, gif.dispose === 3));
120
+ rest.push(gifCodec.encodeFrame(gif, palette, gif.dispose === 3));
119
121
  },
120
122
  file() {
121
123
  const f = first;
122
- return concat([gifCodec.header(width, height, loopCount, comments), gifCodec.encodeFrame(f, quality, f.dispose === 3 || restores), ...rest, new Uint8Array([0x3b])]);
124
+ return concat([gifCodec.header(width, height, loops, comments), gifCodec.encodeFrame(f, palette, f.dispose === 3 || restores), ...rest, new Uint8Array([0x3b])]);
123
125
  }
124
126
  }, optimize);
125
127
  }
126
- static __apng__(width, height, { loopCount = -1, metadata = {}, optimize = true, compression: compressionOption = 4 }) {
128
+ static __apng__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, compression: compressionOption = 4 }) {
127
129
  const compression = compressionLevel(compressionOption);
128
- canvas(width, height, loopCount);
130
+ const loops = fitLoops(loopCount(count), 'APNG');
131
+ canvas(width, height);
129
132
  const text = pngText(resolveMetadata(metadata));
130
133
  const stored = [];
131
134
  const cost = new png.AlphaCost();
@@ -166,16 +169,14 @@ export class AnimationEncoder {
166
169
  const format = scanner.format(), encoded = [];
167
170
  for await (const { pixels, ...f } of frames())
168
171
  encoded.push({ ...f, data: await png.frameData(pixels, f.width, f.height, format, compression) });
169
- return png.animationFile(encoded, width, height, toPlays(loopCount), format, text);
172
+ return png.animationFile(encoded, width, height, toPlays(loops), format, text);
170
173
  }
171
174
  }, optimize);
172
175
  }
173
176
  }
174
- function canvas(width, height, loopCount) {
177
+ function canvas(width, height) {
175
178
  if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1)
176
179
  throw new RangeError(`Invalid canvas size: ${width}x${height}`);
177
- if (loopCount !== Infinity && (!Number.isInteger(loopCount) || loopCount < -1))
178
- throw new RangeError('Invalid loop count');
179
180
  }
180
181
  function webpFrame(f) {
181
182
  let { x, y, width: w, height: h, pixels } = f;
@@ -1,52 +1,28 @@
1
1
  import { BinaryData } from './util/mem.js';
2
- import type { ToneMapping } from './codecs/hdr.js';
3
- import { ResizeMode, ResizeOptions, ResizeToOptions } from './image.js';
2
+ import { DecodeOptions, EncodeOptions, GIFEncodeOptions, ResizeOptions, ResizeToOptions, RotateOptions, TransformOptions, AffineTransform, ShadowOptions, OutlineOptions, TrimOptions } from './image.js';
4
3
  import { Frame } from './frame.js';
5
- import { Metadata } from './metadata.js';
6
4
  import { AnimationEncoder } from './animation-encoder.js';
7
5
  /** Options of {@link Animation} */
8
6
  export interface AnimationOptions {
9
7
  /**
10
- * How many times to repeat the animation (`Infinity` = forever, 0 = play once, 1 = play twice, ...). `-1` still
11
- * means forever, it will be removed in 4.0. Default: forever
8
+ * How many times to repeat the animation: `Infinity` loops forever, 0 plays once, 1 plays twice, ... Anything else
9
+ * throws: a RangeError unless it is an integer from 0 or `Infinity`, a TypeError unless it is a number. Default:
10
+ * `Infinity`
12
11
  */
13
12
  loopCount?: number;
14
13
  }
15
- /** Options of {@link Animation.decode} */
16
- export interface AnimationDecodeOptions {
17
- /** Whether to stop decoding after the first frame. Default: `false` */
18
- onlyFirstFrame?: boolean;
14
+ /** Options of {@link Animation}'s constructor: the canvas size and the loop count */
15
+ export interface AnimationCanvasOptions extends AnimationOptions {
19
16
  /**
20
- * The most pixels to decode, of all frames together (every frame is a full canvas): larger animations throw a
21
- * RangeError before anything that size is allocated, so small files declaring huge animations (decompression
22
- * bombs) can't exhaust the memory. Default: `268402689` (16383², like sharp), `Infinity` for no limit
17
+ * The canvas width in pixels: frames (or the parts of them) outside the canvas aren't encoded. Default: the
18
+ * frames' right edge (the largest `xOffset + width`), following the frames until a canvas size is set
23
19
  */
24
- maxPixels?: number;
25
- /** Whether to convert the colors of frames with an embedded ICC profile (APNGs, WebPs) to sRGB, like `applyColorProfile` of {@link Image.decode}. Default: `true` */
26
- applyColorProfile?: boolean;
27
- /** At most this many worker threads decode in parallel, like `threads` of {@link Image.decode}. Default: the processors available, at most 8 */
28
- threads?: number;
29
- /**
30
- * Whether to rotate/mirror the frames as the orientation tag (Exif, JPEG XL's header, PNG's eXIf chunk or XMP)
31
- * says, like `applyOrientation` of {@link Image.decode}: APNGs, animated WebPs and JPEG XLs. Default: `true`
32
- */
33
- applyOrientation?: boolean;
34
- /**
35
- * How HDR (PQ or HLG) JPEG XL animations, whose light can be brighter than (SDR) white, become 8 bit sRGB, like
36
- * `toneMapping` of {@link Image.decode}: `'reinhard'` compresses the brightest parts, `'clamp'` clamps everything
37
- * brighter than white. Default: `'reinhard'`
38
- */
39
- toneMapping?: ToneMapping;
40
- /**
41
- * Whether to read the gain map (jhgm box) of JPEG XL animations into {@link Image.gainMap} of every frame, like
42
- * `gainMap` of {@link Image.decode}. Default: `true`
43
- */
44
- gainMap?: boolean;
20
+ width?: number;
21
+ /** The canvas height in pixels, like `width`. Default: the frames' bottom edge (the largest `yOffset + height`) */
22
+ height?: number;
45
23
  }
46
24
  /** The options all animation encoders have */
47
- export interface AnimationEncodeOptions {
48
- /** Metadata to include, see {@link Metadata} */
49
- metadata?: Metadata;
25
+ export interface AnimationEncodeOptions extends EncodeOptions {
50
26
  /**
51
27
  * Whether to store each frame as the area that changed since the frame before and merge identical frames, which
52
28
  * usually makes files a lot smaller. The file shows the same animation either way, but only decodes to the same
@@ -57,22 +33,22 @@ export interface AnimationEncodeOptions {
57
33
  /** Options of {@link Animation.encodeWebP} */
58
34
  export interface WebPAnimationEncodeOptions extends AnimationEncodeOptions {
59
35
  /**
60
- * Lossy frames (0-100, like libwebp's quality: 75 is its default), much smaller than lossless ones. Without it the
61
- * frames are lossless. Optimized lossy frames, like libwebp's, leave out 8x8 blocks that only changed a little (by
62
- * up to 3 per channel at quality 85, 1 at 100)
36
+ * Lossy compression quality (0-100): higher values usually preserve more detail but make larger files. Without
37
+ * this option, frames are encoded losslessly
63
38
  */
64
39
  quality?: number;
65
- /** How much effort the frames take (0-6, lossy and lossless), see {@link WebPEncodeOptions.effort}. Default: `2` */
40
+ /**
41
+ * Compression effort (0-6): higher effort can make smaller files but takes longer, see
42
+ * {@link WebPEncodeOptions.effort}. Default: `2`
43
+ */
66
44
  effort?: number;
67
- /** Lossy frames: libwebp's sharp YUV conversion, see {@link WebPEncodeOptions.sharpYuv}. Default: `false` */
45
+ /** For lossy frames, improve color detail around sharp edges. Default: `false` */
68
46
  sharpYuv?: boolean;
69
- /** Lossy frames: the alpha planes' quality (0-100), see {@link WebPEncodeOptions.alphaQuality}. Default: `100` */
47
+ /** For lossy frames, the quality of the transparency channel (0-100). Default: `100` */
70
48
  alphaQuality?: number;
71
49
  }
72
- /** Options of {@link Animation.encodeGIF} */
73
- export interface GIFEncodeOptions extends AnimationEncodeOptions {
74
- /** 1-100, scales the palette size from 8 colors (1) to 256 colors (90 and above). Default: `95` */
75
- quality?: number;
50
+ /** Options of {@link Animation.encodeGIF} and {@link Animation.gifEncoder}: the palette of {@link GIFEncodeOptions} and the animation options */
51
+ export interface GIFAnimationEncodeOptions extends GIFEncodeOptions, AnimationEncodeOptions {
76
52
  }
77
53
  /** Options of {@link Animation.encodeAPNG} */
78
54
  export interface APNGEncodeOptions extends AnimationEncodeOptions {
@@ -80,60 +56,54 @@ export interface APNGEncodeOptions extends AnimationEncodeOptions {
80
56
  compression?: number;
81
57
  }
82
58
  /**
83
- * An animation: frames ({@link Animation.frames}) that can be decoded from and encoded to GIF, APNG and WebP.
84
- *
85
- * The animation itself is an array of its frames too (`animation[0]`, `animation.map(...)`), which is deprecated: in 4.0
86
- * it won't extend `Array` anymore, use {@link Animation.frames} instead. Array methods like map and filter return
87
- * plain arrays.
59
+ * An animation: frames ({@link Animation.frames}) that can be decoded from and encoded to GIF, APNG and WebP. It can be
60
+ * iterated (`for (const frame of animation)`), and its `length` is the number of frames.
88
61
  */
89
- export declare class Animation extends Array<Frame> {
90
- /**
91
- * How many times to repeat the animation (`Infinity` = forever, 0 = play once, 1 = play twice, ...). `-1` still
92
- * means forever, it will be removed in 4.0, when `Infinity` is what animations that loop forever have (animations
93
- * that loop forever have `-1` until then, also the decoded ones)
94
- */
95
- loopCount: number;
62
+ export declare class Animation {
96
63
  /**
97
64
  * Creates a new animation
98
65
  * @param frames The frames to create the animation from
99
- * @param options See {@link AnimationOptions}
66
+ * @param options The canvas size and the loop count, see {@link AnimationCanvasOptions}
100
67
  */
101
- constructor(frames: Frame[], options?: AnimationOptions);
68
+ constructor(frames: Frame[], options?: AnimationCanvasOptions);
102
69
  /**
103
- * Creates a new animation
104
- * @param frames The frames to create the animation from
105
- * @param loopCount How many times to repeat the animation (`Infinity` = forever, 0 = play once, 1 = play twice, ...)
106
- * @deprecated Pass {@link AnimationOptions} instead, the positional arguments will be removed in 4.0
70
+ * How many times to repeat the animation: `Infinity` (the default) loops forever, 0 plays once, 1 plays twice, ...
71
+ * Other values throw, see {@link AnimationOptions.loopCount}, and the loop count stays as it was
107
72
  */
108
- constructor(frames: Frame[], loopCount?: number);
73
+ get loopCount(): number;
109
74
  /**
110
- * The animation's frames: an array that changes the animation when it's changed (e.g. `push()`, `splice()`, or
111
- * setting an index), and can be replaced as a whole
75
+ * Replaces the loop count (see {@link Animation.loopCount}). Anything else than `Infinity` or an integer from 0
76
+ * throws, and the count stays as it was
77
+ * @param value The new loop count
112
78
  */
113
- get frames(): Frame[];
79
+ set loopCount(value: number);
80
+ /**
81
+ * The animation's frames as a frozen array. The frames themselves are mutable; assign a new array to replace the
82
+ * list
83
+ */
84
+ get frames(): readonly Frame[];
114
85
  /**
115
86
  * Replaces the animation's frames
116
- * @param frames The new frames (copied into the animation, the array itself isn't kept)
87
+ * @param frames The new frames (copied into the animation; the array itself isn't kept)
88
+ */
89
+ set frames(frames: readonly Frame[]);
90
+ /** The number of frames */
91
+ get length(): number;
92
+ /** Iterates over the frames, `for (const frame of animation)` */
93
+ [Symbol.iterator](): IterableIterator<Frame>;
94
+ /**
95
+ * The canvas width: the one given to the constructor, the decoded file's, or the one {@link Animation.resize} and
96
+ * {@link Animation.crop} set; else the frames' right edge
117
97
  */
118
- set frames(frames: Frame[]);
119
- /** The animation's width */
120
98
  get width(): number;
121
- /** The animation's height */
99
+ /** The canvas height, like {@link Animation.width}; else the frames' bottom edge */
122
100
  get height(): number;
101
+ /** Clones the animation: its frames (with their pixels), canvas size and loop count */
102
+ clone(): Animation;
123
103
  /** The animation's duration (in ms) */
124
104
  get duration(): number;
125
105
  /** A short description for debugging, e.g. `Animation<64x64x1000ms>` */
126
106
  toString(): string;
127
- /**
128
- * Returns a new animation of the same class containing a range of this one's frames
129
- * (same semantics as Array.prototype.slice)
130
- * @param start The index of the first frame (negative counts from the end). Default: `0`
131
- * @param end The index after the last frame (negative counts from the end). Default: the frame count
132
- * @deprecated Use `new Animation(animation.frames.slice(start, end), animation.loopCount)`: in 4.0 animations
133
- * aren't arrays anymore
134
- * @group Deprecated
135
- */
136
- slice(start?: number, end?: number): this;
137
107
  /**
138
108
  * Resizes the animation to the given dimensions, scaling every frame and its offsets proportionally.
139
109
  * Pass {@link ResizeToOptions} with only a width or a height to keep the aspect ratio.
@@ -142,15 +112,6 @@ export declare class Animation extends Array<Frame> {
142
112
  * @param options See {@link ResizeOptions}
143
113
  */
144
114
  resize(width: number, height: number, options?: ResizeOptions): this;
145
- /**
146
- * Resizes the animation to the given dimensions, scaling every frame and its offsets proportionally.
147
- * Pass {@link ResizeToOptions} with only a width or a height to keep the aspect ratio.
148
- * @param width The new width
149
- * @param height The new height
150
- * @param mode The resizing mode to use. Default: {@link ResizeModes.BILINEAR}
151
- * @deprecated Pass {@link ResizeOptions} with `mode` instead, the positional mode will be removed in 4.0
152
- */
153
- resize(width: number, height: number, mode?: ResizeMode): this;
154
115
  /**
155
116
  * Resizes the animation, scaling every frame and its offsets proportionally: to the given width or height (the
156
117
  * other side keeps the aspect ratio), or to both
@@ -158,22 +119,63 @@ export declare class Animation extends Array<Frame> {
158
119
  */
159
120
  resize(options: ResizeToOptions): this;
160
121
  /**
161
- * Encodes the animation as GIF. Like all encoders, it stores each frame as the area that changed since the frame
162
- * before and merges identical frames (unless the `optimize` option is false), so the file decodes to what the
163
- * animation shows, but not necessarily to the same frames. Semi-transparent pixels become opaque or transparent
164
- * after the frames are composited
165
- * @param options See {@link GIFEncodeOptions}
122
+ * Crops the canvas to the given region: the frames move with it and are cut to the new canvas. The region is
123
+ * clipped to the canvas, so the result can be smaller than the requested size
124
+ * @param x The x offset (0-based)
125
+ * @param y The y offset (0-based)
126
+ * @param width The new canvas width
127
+ * @param height The new canvas height
128
+ */
129
+ crop(x: number, y: number, width: number, height: number): this;
130
+ /**
131
+ * Scales the animation by a factor: every frame and its offsets, and the canvas
132
+ * @param factor The factor
133
+ * @param options See {@link ResizeOptions}
134
+ */
135
+ scale(factor: number, options?: ResizeOptions): this;
136
+ /**
137
+ * Trims the canvas: removes the borders of one color around what any frame shows (in the composited animation),
138
+ * like {@link Image.trim}. The frames keep their pixels, the canvas is cropped like {@link Animation.crop}
139
+ * @param options The color (by default the top left pixel of the first frame) and the tolerance, see
140
+ * {@link TrimOptions}
141
+ */
142
+ trim(options?: TrimOptions): this;
143
+ /**
144
+ * Rotates the animation clockwise, like {@link Image.rotate}: the frames become full canvas frames of the
145
+ * composited animation (a partial frame turned by any angle wouldn't cover a rectangle anymore), each one rotated,
146
+ * and the canvas takes their size
147
+ * @param angle The angle in degrees, clockwise
148
+ * @param options See {@link RotateOptions}
149
+ */
150
+ rotate(angle: number, options?: RotateOptions): this;
151
+ /**
152
+ * Transforms the animation with an affine transform, like {@link Image.transform}: the frames become full canvas
153
+ * frames of the composited animation, each one transformed (by default around the canvas' middle), and the canvas
154
+ * takes their size
155
+ * @param matrix The six values [a, b, c, d, e, f]
156
+ * @param options See {@link TransformOptions}
157
+ */
158
+ transform(matrix: AffineTransform, options?: TransformOptions): this;
159
+ /**
160
+ * Adds a shadow behind what the animation shows, like {@link Image.dropShadow}: the frames become full canvas
161
+ * frames of the composited animation, each one with its shadow, and the canvas grows with them
162
+ * @param options See {@link ShadowOptions}
163
+ */
164
+ dropShadow(options?: ShadowOptions): this;
165
+ /**
166
+ * Draws an outline around what the animation shows, like {@link Image.outline}: the frames become full canvas
167
+ * frames of the composited animation, each one outlined, and the canvas grows with them
168
+ * @param options See {@link OutlineOptions}
166
169
  */
167
- encodeGIF(options?: GIFEncodeOptions): Promise<Uint8Array>;
170
+ outline(options?: OutlineOptions): this;
168
171
  /**
169
172
  * Encodes the animation as GIF. Like all encoders, it stores each frame as the area that changed since the frame
170
173
  * before and merges identical frames (unless the `optimize` option is false), so the file decodes to what the
171
174
  * animation shows, but not necessarily to the same frames. Semi-transparent pixels become opaque or transparent
172
175
  * after the frames are composited
173
- * @param quality 1-100, scales the palette size from 8 colors (1) to 256 colors (90 and above)
174
- * @deprecated Pass {@link GIFEncodeOptions} instead, the positional arguments will be removed in 4.0
176
+ * @param options See {@link GIFAnimationEncodeOptions}
175
177
  */
176
- encodeGIF(quality?: number): Promise<Uint8Array>;
178
+ encodeGIF(options?: GIFAnimationEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
177
179
  /**
178
180
  * Encodes the animation as APNG (animated PNG, lossless and with full alpha). Viewers without APNG support show
179
181
  * the first frame. Each frame is stored as the area that changed since the frame before, identical frames are
@@ -181,23 +183,14 @@ export declare class Animation extends Array<Frame> {
181
183
  * necessarily decode to the same frames
182
184
  * @param options See {@link APNGEncodeOptions}
183
185
  */
184
- encodeAPNG(options?: APNGEncodeOptions): Promise<Uint8Array>;
185
- /**
186
- * Encodes the animation as APNG (animated PNG, lossless and with full alpha). Viewers without APNG support show
187
- * the first frame. Each frame is stored as the area that changed since the frame before, identical frames are
188
- * merged (unless the `optimize` option is false): the file shows exactly the same animation, but doesn't
189
- * necessarily decode to the same frames
190
- * @param compression The zlib compression level (0-9), higher is smaller but slower. Default: `4`
191
- * @deprecated Pass {@link APNGEncodeOptions} instead, the positional arguments will be removed in 4.0
192
- */
193
- encodeAPNG(compression?: number): Promise<Uint8Array>;
186
+ encodeAPNG(options?: APNGEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
194
187
  /**
195
188
  * Encodes the animation as animated WebP, lossless or (with a quality) lossy. Each frame is stored as the area that
196
189
  * changed since the frame before, identical frames are merged (unless the `optimize` option is false): the file
197
190
  * shows the same animation, but doesn't necessarily decode to the same frames
198
191
  * @param options See {@link WebPAnimationEncodeOptions}
199
192
  */
200
- encodeWebP({ metadata, optimize, quality, effort, sharpYuv, alphaQuality }?: WebPAnimationEncodeOptions): Promise<Uint8Array>;
193
+ encodeWebP(options?: WebPAnimationEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
201
194
  /**
202
195
  * An encoder that makes an animated WebP a frame at a time, like {@link Animation.encodeWebP} (the same file),
203
196
  * without keeping the frames in memory: `await encoder.add(frame)` for each frame (a {@link Frame}, or an image
@@ -212,9 +205,9 @@ export declare class Animation extends Array<Frame> {
212
205
  * without keeping the frames in memory: `await encoder.add(frame)` for each frame, then `await encoder.finish()`
213
206
  * @param width The canvas width
214
207
  * @param height The canvas height
215
- * @param options See {@link GIFEncodeOptions}, and {@link AnimationOptions.loopCount}
208
+ * @param options See {@link GIFAnimationEncodeOptions}, and {@link AnimationOptions.loopCount}
216
209
  */
217
- static gifEncoder(width: number, height: number, options?: GIFEncodeOptions & AnimationOptions): AnimationEncoder;
210
+ static gifEncoder(width: number, height: number, options?: GIFAnimationEncodeOptions & AnimationOptions): AnimationEncoder;
218
211
  /**
219
212
  * An encoder that makes an APNG a frame at a time, like {@link Animation.encodeAPNG} (the same file), keeping the
220
213
  * frames only compressed (the pixel format depends on all of them): `await encoder.add(frame)` for each frame,
@@ -227,14 +220,7 @@ export declare class Animation extends Array<Frame> {
227
220
  /**
228
221
  * Decodes an animated GIF, APNG, WebP or JPEG XL into fully composited frames (still images become a single frame)
229
222
  * @param input The binary data to decode
230
- * @param options See {@link AnimationDecodeOptions}
231
- */
232
- static decode(input: BinaryData, options?: AnimationDecodeOptions): Promise<Animation>;
233
- /**
234
- * Decodes an animated GIF, APNG, WebP or JPEG XL into fully composited frames (still images become a single frame)
235
- * @param input The binary data to decode
236
- * @param onlyExtractFirstFrame Whether to stop decoding after the first frame
237
- * @deprecated Pass {@link AnimationDecodeOptions} instead, the positional arguments will be removed in 4.0
223
+ * @param options See {@link DecodeOptions}
238
224
  */
239
- static decode(input: BinaryData, onlyExtractFirstFrame?: boolean): Promise<Animation>;
225
+ static decode(input: BinaryData, options?: DecodeOptions): Promise<Animation>;
240
226
  }