imagescript 4.0.0-rc.2 → 4.0.0-rc.4
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 +10 -1
- package/dist/animation-encoder.d.ts +14 -6
- package/dist/animation-encoder.js +24 -9
- package/dist/animation.d.ts +68 -28
- package/dist/animation.js +82 -27
- package/dist/codecs/gif.js +16 -5
- package/dist/codecs/jpeg.js +2 -0
- package/dist/codecs/jxl/frame-header.js +6 -4
- package/dist/codecs/jxl/frame.js +4 -1
- package/dist/codecs/png.js +46 -20
- package/dist/codecs/quantize.js +25 -13
- package/dist/codecs/tiff.js +7 -0
- package/dist/codecs/webp.js +19 -18
- package/dist/colors.js +25 -17
- package/dist/frame.d.ts +18 -5
- package/dist/gainmap.d.ts +43 -14
- package/dist/gainmap.js +25 -16
- package/dist/image.d.ts +430 -173
- package/dist/image.js +109 -101
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/metadata.d.ts +11 -5
- package/dist/metadata.js +1 -1
- package/dist/package.json +1 -1
- package/dist/render/svg.js +172 -64
- package/dist/render/text.js +10 -8
- package/dist/text-layout.d.ts +28 -12
- package/dist/text-layout.js +17 -30
- package/dist/util/limits.d.ts +40 -0
- package/dist/util/limits.js +5 -0
- package/dist/util/options.js +44 -3
- package/dist/util/rotate.js +43 -0
- package/package.json +1 -2
package/README.md
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
**ImageScript** decodes, edits and encodes images in pure TypeScript: no WebAssembly, no native binaries, and no
|
|
17
17
|
runtime dependencies. It runs in Node.js 22.13+, Deno, Bun, browsers and edge runtimes (Cloudflare Workers, Vercel's
|
|
18
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
|
|
19
|
+
definitions (TypeScript 5.7 or newer: with older versions and `skipLibCheck`, the encoders' return types become `any`). Large AVIF and JPEG XL operations, and lossless WebP encoding, can use multiple CPU cores when the runtime
|
|
20
20
|
supports it.
|
|
21
21
|
|
|
22
22
|
```sh
|
|
@@ -39,6 +39,15 @@ Without a bundler, import it from jsDelivr in the browser:
|
|
|
39
39
|
</script>
|
|
40
40
|
```
|
|
41
41
|
|
|
42
|
+
The codecs that can use worker threads (large AVIF and JPEG XL images, lossless WebP; the `threads` option) do so in
|
|
43
|
+
Node.js, Deno and Bun, and in browsers on cross-origin isolated pages. Where workers can't start, the work runs on the
|
|
44
|
+
calling thread: the output is the same, only slower, and nothing warns about it. Browsers refuse workers from another
|
|
45
|
+
origin, so the jsDelivr example above runs single-threaded; serve the package from your own origin (on a cross-origin
|
|
46
|
+
isolated page) to get threads.
|
|
47
|
+
|
|
48
|
+
Bundlers that write one file (esbuild, webpack) don't copy the worker's module: serve `dist/util/worker.js` next to the
|
|
49
|
+
bundle, or the same single-threaded fallback is used. Vite and Rollup emit it.
|
|
50
|
+
|
|
42
51
|
---
|
|
43
52
|
|
|
44
53
|
### Example
|
|
@@ -2,11 +2,12 @@ import { Image } from './image.js';
|
|
|
2
2
|
import { Frame, FrameOptions } from './frame.js';
|
|
3
3
|
/**
|
|
4
4
|
* Encodes an animation a frame at a time, without keeping all frames in memory: see {@link Animation.webpEncoder},
|
|
5
|
-
* {@link Animation.gifEncoder} and {@link Animation.apngEncoder}
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
5
|
+
* {@link Animation.gifEncoder} and {@link Animation.apngEncoder}
|
|
6
|
+
* @remarks
|
|
7
|
+
* The file is the one an {@link Animation} of the frames encodes to, but for unoptimized WebPs with frames WebP can't
|
|
8
|
+
* store as they are (disposed to the previous frame, or disposed with odd offsets): from the first of them on, the
|
|
9
|
+
* frames are the canvas they show (the same animation, blending rounds differently by 1 at most). APNGs keep their
|
|
10
|
+
* frames compressed until the end: their pixel format depends on all of them
|
|
10
11
|
*/
|
|
11
12
|
export declare class AnimationEncoder {
|
|
12
13
|
private readonly format;
|
|
@@ -18,6 +19,7 @@ export declare class AnimationEncoder {
|
|
|
18
19
|
readonly width: number;
|
|
19
20
|
/** The canvas height */
|
|
20
21
|
readonly height: number;
|
|
22
|
+
private constructor();
|
|
21
23
|
/** How many frames were added */
|
|
22
24
|
get frameCount(): number;
|
|
23
25
|
/**
|
|
@@ -25,8 +27,14 @@ export declare class AnimationEncoder {
|
|
|
25
27
|
* default). The options override the frame's. The pixels are copied right away, the image can change afterwards
|
|
26
28
|
* @param frame The frame or image
|
|
27
29
|
* @param options See {@link FrameOptions}
|
|
30
|
+
* @throws `TypeError` if the frame isn't a {@link Frame} or an {@link Image}
|
|
31
|
+
* @throws `RangeError` if the duration is negative or more than the format stores
|
|
32
|
+
* @throws `Error` if the encoder is finished
|
|
28
33
|
*/
|
|
29
34
|
add(frame: Frame | Image, options?: FrameOptions): Promise<void>;
|
|
30
|
-
/**
|
|
35
|
+
/**
|
|
36
|
+
* Encodes the rest and returns the file. The encoder can't be used afterwards
|
|
37
|
+
* @throws `Error` if no frame was added, or the encoder is finished already
|
|
38
|
+
*/
|
|
31
39
|
finish(): Promise<Uint8Array<ArrayBuffer>>;
|
|
32
40
|
}
|
|
@@ -8,6 +8,18 @@ import { Optimizer, Compositor, coverCanvas, fillUnchanged } from "./util/optimi
|
|
|
8
8
|
import { compressAsync, decompressAsync } from "./codecs/zlib.js";
|
|
9
9
|
import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
|
|
10
10
|
import { checkOptions, finite, compressionLevel, loopCount, toPlays, fitLoops, fitDuration, maxDuration } from "./util/options.js";
|
|
11
|
+
function clipToCanvas(frame, width, height) {
|
|
12
|
+
const { x, y, width: w, height: h } = frame;
|
|
13
|
+
if (x >= 0 && y >= 0 && x + w <= width && y + h <= height)
|
|
14
|
+
return frame;
|
|
15
|
+
const left = Math.max(0, x), top = Math.max(0, y), right = Math.min(width, x + w), bottom = Math.min(height, y + h);
|
|
16
|
+
if (right <= left || bottom <= top)
|
|
17
|
+
return { ...frame, x: 0, y: 0, width: 1, height: 1, disposal: 1, dispose: 0, pixels: new Uint8Array(4) };
|
|
18
|
+
const pixels = new Uint8Array((right - left) * (bottom - top) * 4);
|
|
19
|
+
for (let row = top; row < bottom; row++)
|
|
20
|
+
pixels.set(frame.pixels.subarray(((row - y) * w + left - x) * 4, ((row - y) * w + right - x) * 4), (row - top) * (right - left) * 4);
|
|
21
|
+
return { ...frame, x: left, y: top, width: right - left, height: bottom - top, pixels };
|
|
22
|
+
}
|
|
11
23
|
export class AnimationEncoder {
|
|
12
24
|
format;
|
|
13
25
|
optimizer;
|
|
@@ -25,7 +37,7 @@ export class AnimationEncoder {
|
|
|
25
37
|
get frameCount() {
|
|
26
38
|
return this.count;
|
|
27
39
|
}
|
|
28
|
-
add(frame, options = {}) {
|
|
40
|
+
async add(frame, options = {}) {
|
|
29
41
|
checkOptions(options, 'encoder.add(frame, { duration: 40 })');
|
|
30
42
|
if (this.finished)
|
|
31
43
|
throw new Error('The animation encoder is finished');
|
|
@@ -33,12 +45,12 @@ export class AnimationEncoder {
|
|
|
33
45
|
const image = own ? own.image : frame;
|
|
34
46
|
if (!(image instanceof Image))
|
|
35
47
|
throw new TypeError('encoder.add() takes a Frame or an Image');
|
|
36
|
-
const duration = finite(options.duration
|
|
48
|
+
const duration = finite(options.duration === undefined ? own?.duration ?? 100 : options.duration, 'frame duration');
|
|
37
49
|
if (duration < 0)
|
|
38
50
|
throw new RangeError('Invalid frame duration');
|
|
39
51
|
fitDuration(duration, this.format.name);
|
|
40
|
-
const x = Math.trunc(finite(options.xOffset
|
|
41
|
-
const y = Math.trunc(finite(options.yOffset
|
|
52
|
+
const x = Math.trunc(finite(options.xOffset === undefined ? own?.xOffset ?? 0 : options.xOffset, 'x offset')) || 0;
|
|
53
|
+
const y = Math.trunc(finite(options.yOffset === undefined ? own?.yOffset ?? 0 : options.yOffset, 'y offset')) || 0;
|
|
42
54
|
const disposal = options.disposalMode !== undefined ? Frame.__convert_disposal_mode__(options.disposalMode) : own ? own.__disposal_id__ : 1;
|
|
43
55
|
const input = {
|
|
44
56
|
x, y, width: image.width, height: image.height, duration, disposal,
|
|
@@ -46,9 +58,10 @@ export class AnimationEncoder {
|
|
|
46
58
|
pixels: new Uint8Array(image.bitmap.buffer, image.bitmap.byteOffset, image.bitmap.byteLength).slice()
|
|
47
59
|
};
|
|
48
60
|
this.count++;
|
|
61
|
+
const given = this.optimizer ? input : clipToCanvas(input, this.width, this.height);
|
|
49
62
|
return this.queue = this.queue.then(async () => {
|
|
50
63
|
if (!this.optimizer)
|
|
51
|
-
return this.format.frame(
|
|
64
|
+
return this.format.frame(given, false);
|
|
52
65
|
this.optimizer.push(input);
|
|
53
66
|
for (const f of this.optimizer.take())
|
|
54
67
|
await this.format.frame(f, true);
|
|
@@ -70,7 +83,7 @@ export class AnimationEncoder {
|
|
|
70
83
|
}
|
|
71
84
|
static __webp__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 }) {
|
|
72
85
|
const loops = fitLoops(loopCount(count), 'WebP');
|
|
73
|
-
canvas(width, height);
|
|
86
|
+
canvas(width, height, 'WebP');
|
|
74
87
|
if (width > 1 << 24 || height > 1 << 24)
|
|
75
88
|
throw new RangeError('WebP: canvas too large');
|
|
76
89
|
const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
|
|
@@ -102,7 +115,7 @@ export class AnimationEncoder {
|
|
|
102
115
|
const checked = paletteOptions(colors, dither, ditherStrength);
|
|
103
116
|
const palette = { colors: checked.colors, dither: checked.dither, strength: checked.strength };
|
|
104
117
|
const loops = fitLoops(loopCount(count), 'GIF');
|
|
105
|
-
canvas(width, height);
|
|
118
|
+
canvas(width, height, 'GIF');
|
|
106
119
|
const comments = gifComments(resolveMetadata(metadata));
|
|
107
120
|
let first = null, restores = false;
|
|
108
121
|
const rest = [];
|
|
@@ -130,7 +143,7 @@ export class AnimationEncoder {
|
|
|
130
143
|
static __apng__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, compression: compressionOption = 4 }) {
|
|
131
144
|
const compression = compressionLevel(compressionOption);
|
|
132
145
|
const loops = fitLoops(loopCount(count), 'APNG');
|
|
133
|
-
canvas(width, height);
|
|
146
|
+
canvas(width, height, 'APNG');
|
|
134
147
|
const text = pngText(resolveMetadata(metadata));
|
|
135
148
|
const stored = [];
|
|
136
149
|
const cost = new png.AlphaCost();
|
|
@@ -177,9 +190,11 @@ export class AnimationEncoder {
|
|
|
177
190
|
}, optimize);
|
|
178
191
|
}
|
|
179
192
|
}
|
|
180
|
-
function canvas(width, height) {
|
|
193
|
+
function canvas(width, height, format) {
|
|
181
194
|
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1)
|
|
182
195
|
throw new RangeError(`Invalid canvas size: ${width}x${height}`);
|
|
196
|
+
if (format === 'GIF' && (width > 0xffff || height > 0xffff))
|
|
197
|
+
throw new RangeError(`GIF: images can be at most 65535 pixels wide and high, not ${width}x${height}`);
|
|
183
198
|
}
|
|
184
199
|
function webpFrame(f) {
|
|
185
200
|
let { x, y, width: w, height: h, pixels } = f;
|
package/dist/animation.d.ts
CHANGED
|
@@ -1,24 +1,28 @@
|
|
|
1
1
|
import { BinaryData } from './util/mem.js';
|
|
2
|
-
import { DecodeOptions, EncodeOptions, GIFEncodeOptions, ResizeOptions, ResizeToOptions, RotateOptions, TransformOptions, AffineTransform, ShadowOptions, OutlineOptions, TrimOptions } from './image.js';
|
|
2
|
+
import { DecodeOptions, EncodeOptions, GIFEncodeOptions, ResizeOptions, ResizeToOptions, RotateOptions, TransformOptions, AffineTransform, ShadowOptions, OutlineOptions, TrimOptions, PNGEncodeOptions, WebPEncodeOptions, FlipDirection } from './image.js';
|
|
3
3
|
import { Frame } from './frame.js';
|
|
4
4
|
import { AnimationEncoder } from './animation-encoder.js';
|
|
5
5
|
/** Options of {@link Animation} */
|
|
6
6
|
export interface AnimationOptions {
|
|
7
7
|
/**
|
|
8
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
|
|
10
|
-
* `Infinity`
|
|
9
|
+
* throws: a RangeError unless it is an integer from 0 or `Infinity`, a TypeError unless it is a number
|
|
10
|
+
* @defaultValue `Infinity`
|
|
11
11
|
*/
|
|
12
12
|
loopCount?: number;
|
|
13
13
|
}
|
|
14
14
|
/** Options of {@link Animation}'s constructor: the canvas size and the loop count */
|
|
15
15
|
export interface AnimationCanvasOptions extends AnimationOptions {
|
|
16
16
|
/**
|
|
17
|
-
* The canvas width in pixels: frames (or the parts of them) outside the canvas aren't encoded
|
|
18
|
-
* frames' right edge (the largest `xOffset + width`), following the frames until a canvas size is
|
|
17
|
+
* The canvas width in pixels: frames (or the parts of them) outside the canvas aren't encoded
|
|
18
|
+
* @defaultValue The frames' right edge (the largest `xOffset + width`), following the frames until a canvas size is
|
|
19
|
+
* set
|
|
19
20
|
*/
|
|
20
21
|
width?: number;
|
|
21
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* The canvas height in pixels, like `width`
|
|
24
|
+
* @defaultValue The frames' bottom edge (the largest `yOffset + height`)
|
|
25
|
+
*/
|
|
22
26
|
height?: number;
|
|
23
27
|
}
|
|
24
28
|
/** The options all animation encoders have */
|
|
@@ -26,34 +30,31 @@ export interface AnimationEncodeOptions extends EncodeOptions {
|
|
|
26
30
|
/**
|
|
27
31
|
* Whether to store each frame as the area that changed since the frame before and merge identical frames, which
|
|
28
32
|
* usually makes files a lot smaller. The file shows the same animation either way, but only decodes to the same
|
|
29
|
-
* frames without it, which also encodes faster when little changes.
|
|
33
|
+
* frames without it, which also encodes faster when little changes. The exception is GIF, which has no partial
|
|
34
|
+
* transparency: without `optimize`, a semi-transparent pixel becomes opaque or transparent in its own frame, with
|
|
35
|
+
* it the frames are composited first
|
|
36
|
+
* @defaultValue `true`
|
|
30
37
|
*/
|
|
31
38
|
optimize?: boolean;
|
|
32
39
|
}
|
|
33
|
-
/**
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
quality?: number;
|
|
40
|
-
/**
|
|
41
|
-
* Compression effort (0-6): higher effort can make smaller files but takes longer, see
|
|
42
|
-
* {@link WebPEncodeOptions.effort}. Default: `2`
|
|
43
|
-
*/
|
|
44
|
-
effort?: number;
|
|
45
|
-
/** For lossy frames, improve color detail around sharp edges. Default: `false` */
|
|
46
|
-
sharpYuv?: boolean;
|
|
47
|
-
/** For lossy frames, the quality of the transparency channel (0-100). Default: `100` */
|
|
48
|
-
alphaQuality?: number;
|
|
40
|
+
/**
|
|
41
|
+
* Options of {@link Animation.encodeWebP} and {@link Animation.webpEncoder}: those of {@link WebPEncodeOptions} for every
|
|
42
|
+
* frame (but `threads`: the frames are encoded one at a time), and the animation options. Without `quality` the frames
|
|
43
|
+
* are lossless
|
|
44
|
+
*/
|
|
45
|
+
export interface WebPAnimationEncodeOptions extends Omit<WebPEncodeOptions, 'threads'>, AnimationEncodeOptions {
|
|
49
46
|
}
|
|
50
|
-
/**
|
|
47
|
+
/**
|
|
48
|
+
* Options of {@link Animation.encodeGIF} and {@link Animation.gifEncoder}: those of {@link GIFEncodeOptions} for every
|
|
49
|
+
* frame, and the animation options
|
|
50
|
+
*/
|
|
51
51
|
export interface GIFAnimationEncodeOptions extends GIFEncodeOptions, AnimationEncodeOptions {
|
|
52
52
|
}
|
|
53
|
-
/**
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Options of {@link Animation.encodeAPNG} and {@link Animation.apngEncoder}: those of {@link PNGEncodeOptions}, and the
|
|
55
|
+
* animation options
|
|
56
|
+
*/
|
|
57
|
+
export interface APNGEncodeOptions extends PNGEncodeOptions, AnimationEncodeOptions {
|
|
57
58
|
}
|
|
58
59
|
/**
|
|
59
60
|
* An animation: frames ({@link Animation.frames}) that can be decoded from and encoded to GIF, APNG and WebP. It can be
|
|
@@ -62,6 +63,14 @@ export interface APNGEncodeOptions extends AnimationEncodeOptions {
|
|
|
62
63
|
export declare class Animation {
|
|
63
64
|
/**
|
|
64
65
|
* Creates a new animation
|
|
66
|
+
* @example
|
|
67
|
+
* ```ts
|
|
68
|
+
* const animation = new Animation([
|
|
69
|
+
* new Frame(new Image(64, 64).fill(0xff0000ff), { duration: 200 }),
|
|
70
|
+
* new Frame(new Image(64, 64).fill(0x0000ffff), { duration: 200 })
|
|
71
|
+
* ], { loopCount: 2 });
|
|
72
|
+
* const gif = await animation.encodeGIF();
|
|
73
|
+
* ```
|
|
65
74
|
* @param frames The frames to create the animation from
|
|
66
75
|
* @param options The canvas size and the loop count, see {@link AnimationCanvasOptions}
|
|
67
76
|
*/
|
|
@@ -107,9 +116,13 @@ export declare class Animation {
|
|
|
107
116
|
/**
|
|
108
117
|
* Resizes the animation to the given dimensions, scaling every frame and its offsets proportionally.
|
|
109
118
|
* Pass {@link ResizeToOptions} with only a width or a height to keep the aspect ratio.
|
|
119
|
+
* @remarks
|
|
120
|
+
* With `fit: 'contain'` and a `background` that isn't transparent, the frames are composited onto it, so the animation
|
|
121
|
+
* has whole frames afterwards (the file shows the same, but it can't keep the frames' parts apart anymore)
|
|
110
122
|
* @param width The new width
|
|
111
123
|
* @param height The new height
|
|
112
124
|
* @param options See {@link ResizeOptions}
|
|
125
|
+
* @throws `RangeError` if the width or height is less than 1 pixel, or the animation has no canvas
|
|
113
126
|
*/
|
|
114
127
|
resize(width: number, height: number, options?: ResizeOptions): this;
|
|
115
128
|
/**
|
|
@@ -127,6 +140,12 @@ export declare class Animation {
|
|
|
127
140
|
* @param height The new canvas height
|
|
128
141
|
*/
|
|
129
142
|
crop(x: number, y: number, width: number, height: number): this;
|
|
143
|
+
/**
|
|
144
|
+
* Flips / mirrors the animation horizontally or vertically, like {@link Image.flip}: every frame is flipped and
|
|
145
|
+
* moved to the mirrored place on the canvas, which keeps its size
|
|
146
|
+
* @param direction The direction to flip, see {@link FlipDirection}
|
|
147
|
+
*/
|
|
148
|
+
flip(direction: FlipDirection): this;
|
|
130
149
|
/**
|
|
131
150
|
* Scales the animation by a factor: every frame and its offsets, and the canvas
|
|
132
151
|
* @param factor The factor
|
|
@@ -174,6 +193,9 @@ export declare class Animation {
|
|
|
174
193
|
* animation shows, but not necessarily to the same frames. Semi-transparent pixels become opaque or transparent
|
|
175
194
|
* after the frames are composited
|
|
176
195
|
* @param options See {@link GIFAnimationEncodeOptions}
|
|
196
|
+
* @throws `Error` if the animation has no frames
|
|
197
|
+
* @throws `RangeError` if the loop count or a frame's duration is more than GIF stores, or the canvas is wider or
|
|
198
|
+
* higher than 65535 pixels
|
|
177
199
|
*/
|
|
178
200
|
encodeGIF(options?: GIFAnimationEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
|
|
179
201
|
/**
|
|
@@ -182,6 +204,8 @@ export declare class Animation {
|
|
|
182
204
|
* merged (unless the `optimize` option is false): the file shows exactly the same animation, but doesn't
|
|
183
205
|
* necessarily decode to the same frames
|
|
184
206
|
* @param options See {@link APNGEncodeOptions}
|
|
207
|
+
* @throws `Error` if the animation has no frames
|
|
208
|
+
* @throws `RangeError` if the loop count or a frame's duration is more than APNG stores
|
|
185
209
|
*/
|
|
186
210
|
encodeAPNG(options?: APNGEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
|
|
187
211
|
/**
|
|
@@ -189,12 +213,21 @@ export declare class Animation {
|
|
|
189
213
|
* changed since the frame before, identical frames are merged (unless the `optimize` option is false): the file
|
|
190
214
|
* shows the same animation, but doesn't necessarily decode to the same frames
|
|
191
215
|
* @param options See {@link WebPAnimationEncodeOptions}
|
|
216
|
+
* @throws `Error` if the animation has no frames
|
|
217
|
+
* @throws `RangeError` if the loop count or a frame's duration is more than WebP stores
|
|
192
218
|
*/
|
|
193
219
|
encodeWebP(options?: WebPAnimationEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
|
|
194
220
|
/**
|
|
195
221
|
* An encoder that makes an animated WebP a frame at a time, like {@link Animation.encodeWebP} (the same file),
|
|
196
222
|
* without keeping the frames in memory: `await encoder.add(frame)` for each frame (a {@link Frame}, or an image
|
|
197
223
|
* with `{ duration }`), then `await encoder.finish()` for the file
|
|
224
|
+
* @example
|
|
225
|
+
* ```ts
|
|
226
|
+
* const encoder = Animation.webpEncoder(64, 64, { quality: 80 });
|
|
227
|
+
* for (const color of [0xff0000ff, 0x00ff00ff, 0x0000ffff])
|
|
228
|
+
* await encoder.add(new Image(64, 64).fill(color), { duration: 200 });
|
|
229
|
+
* const webp = await encoder.finish();
|
|
230
|
+
* ```
|
|
198
231
|
* @param width The canvas width
|
|
199
232
|
* @param height The canvas height
|
|
200
233
|
* @param options See {@link WebPAnimationEncodeOptions}, and {@link AnimationOptions.loopCount}
|
|
@@ -219,8 +252,15 @@ export declare class Animation {
|
|
|
219
252
|
static apngEncoder(width: number, height: number, options?: APNGEncodeOptions & AnimationOptions): AnimationEncoder;
|
|
220
253
|
/**
|
|
221
254
|
* Decodes an animated GIF, APNG, WebP or JPEG XL into fully composited frames (still images become a single frame)
|
|
255
|
+
* @example
|
|
256
|
+
* ```ts
|
|
257
|
+
* const animation = await Animation.decode(gifBytes);
|
|
258
|
+
* const webp = await animation.resize({ width: 320 }).encodeWebP({ quality: 75 });
|
|
259
|
+
* ```
|
|
222
260
|
* @param input The binary data to decode
|
|
223
261
|
* @param options See {@link DecodeOptions}
|
|
262
|
+
* @throws {@link LimitError} if the frames have more than `options.maxPixels` pixels together
|
|
263
|
+
* @throws `Error` if the data isn't a supported image, or is damaged or truncated
|
|
224
264
|
*/
|
|
225
265
|
static decode(input: BinaryData, options?: DecodeOptions): Promise<Animation>;
|
|
226
266
|
}
|
package/dist/animation.js
CHANGED
|
@@ -6,14 +6,14 @@ import * as jxl from "./codecs/jxl.js";
|
|
|
6
6
|
import { availableThreads } from "./util/threads.js";
|
|
7
7
|
import { view } from "./util/mem.js";
|
|
8
8
|
import { GainMap } from "./gainmap.js";
|
|
9
|
-
import { Image, resizeArguments, insideSize, alignedPixels } from "./image.js";
|
|
9
|
+
import { Image, resizeArguments, insideSize, alignedPixels, FLIP_DIRECTIONS, TONE_MAPPINGS } from "./image.js";
|
|
10
10
|
import { Frame } from "./frame.js";
|
|
11
11
|
import { ImageType } from "./image-type.js";
|
|
12
12
|
import { optimize } from "./util/optimize.js";
|
|
13
13
|
import { paletteOptions } from "./codecs/quantize.js";
|
|
14
14
|
import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
|
|
15
|
-
import { checkOptions, finite, compressionLevel, loopCount, toPlays, fromPlays, fitLoops, fitDuration, maxDuration, color as checkColor } from "./util/options.js";
|
|
16
|
-
import { MAX_PIXELS, decoding } from "./util/limits.js";
|
|
15
|
+
import { checkOptions, oneOf, pixelLimit, checkThreads, finite, compressionLevel, loopCount, toPlays, fromPlays, fitLoops, fitDuration, maxDuration, color as checkColor } from "./util/options.js";
|
|
16
|
+
import { MAX_PIXELS, decoding, checkPixels } from "./util/limits.js";
|
|
17
17
|
import { AnimationEncoder } from "./animation-encoder.js";
|
|
18
18
|
function canvasFrames(width, height, frames) {
|
|
19
19
|
return frames.map(({ pixels, duration }) => {
|
|
@@ -106,16 +106,44 @@ export class Animation {
|
|
|
106
106
|
const originalWidth = this.width, originalHeight = this.height;
|
|
107
107
|
if (!originalWidth || !originalHeight)
|
|
108
108
|
throw new RangeError('An animation without frames or canvas can\'t be resized');
|
|
109
|
-
|
|
110
|
-
|
|
109
|
+
if (givenWidth !== undefined && Math.floor(givenWidth) < 1)
|
|
110
|
+
throw new RangeError('The animation has to be at least 1 pixel wide');
|
|
111
|
+
if (givenHeight !== undefined && Math.floor(givenHeight) < 1)
|
|
112
|
+
throw new RangeError('The animation has to be at least 1 pixel high');
|
|
113
|
+
let width, height;
|
|
111
114
|
if (fit === 'inside' && givenWidth !== undefined && givenHeight !== undefined)
|
|
112
|
-
[width, height] = insideSize(originalWidth, originalHeight, givenWidth, givenHeight);
|
|
113
|
-
|
|
115
|
+
[width, height] = insideSize(originalWidth, originalHeight, givenWidth, givenHeight).map(Math.floor);
|
|
116
|
+
else if (givenWidth === undefined) {
|
|
117
|
+
height = Math.floor(givenHeight);
|
|
118
|
+
width = Math.max(1, Math.round(originalWidth / originalHeight * height));
|
|
119
|
+
}
|
|
120
|
+
else if (givenHeight === undefined) {
|
|
121
|
+
width = Math.floor(givenWidth);
|
|
122
|
+
height = Math.max(1, Math.round(originalHeight / originalWidth * width));
|
|
123
|
+
}
|
|
124
|
+
else
|
|
125
|
+
[width, height] = [Math.floor(givenWidth), Math.floor(givenHeight)];
|
|
126
|
+
const canvas = canvasSize(Math.max(1, width), Math.max(1, height));
|
|
114
127
|
const sx = width / originalWidth, sy = height / originalHeight;
|
|
115
|
-
|
|
128
|
+
const changes = this.__distinct__().map(frame => {
|
|
116
129
|
const left = Math.round(frame.xOffset * sx), top = Math.round(frame.yOffset * sy);
|
|
117
130
|
const right = Math.round((frame.xOffset + frame.width) * sx), bottom = Math.round((frame.yOffset + frame.height) * sy);
|
|
118
|
-
frame
|
|
131
|
+
return { frame, left, top, width: Math.max(1, right - left), height: Math.max(1, bottom - top) };
|
|
132
|
+
});
|
|
133
|
+
const shared = new Set(), seen = new Set();
|
|
134
|
+
for (const { frame } of changes)
|
|
135
|
+
(seen.has(frame.image) ? shared : seen).add(frame.image);
|
|
136
|
+
const originals = new Map(Array.from(shared, image => [image, image.clone()]));
|
|
137
|
+
const resized = new Map();
|
|
138
|
+
for (const { frame, left, top, width, height } of changes) {
|
|
139
|
+
const size = `${width}x${height}`, done = resized.get(frame.image), original = originals.get(frame.image);
|
|
140
|
+
if (done === undefined) {
|
|
141
|
+
resized.set(frame.image, size);
|
|
142
|
+
frame.image.resize(width, height, options);
|
|
143
|
+
}
|
|
144
|
+
else if (done !== size && original) {
|
|
145
|
+
frame.image = original.clone().resize(width, height, options);
|
|
146
|
+
}
|
|
119
147
|
frame.xOffset = left;
|
|
120
148
|
frame.yOffset = top;
|
|
121
149
|
}
|
|
@@ -123,17 +151,16 @@ export class Animation {
|
|
|
123
151
|
return this;
|
|
124
152
|
}
|
|
125
153
|
crop(x, y, width, height) {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
if (!(width >= 1 && height >= 1))
|
|
154
|
+
const left = Math.max(0, Math.floor(finite(x, 'x'))), top = Math.max(0, Math.floor(finite(y, 'y')));
|
|
155
|
+
const right = Math.min(this.width, Math.floor(finite(x, 'x')) + Math.floor(finite(width, 'width')));
|
|
156
|
+
const bottom = Math.min(this.height, Math.floor(finite(y, 'y')) + Math.floor(finite(height, 'height')));
|
|
157
|
+
if (!(right - left >= 1 && bottom - top >= 1))
|
|
131
158
|
throw new RangeError('The crop region has to overlap the canvas');
|
|
132
|
-
for (const frame of this.
|
|
133
|
-
frame.xOffset -=
|
|
134
|
-
frame.yOffset -=
|
|
159
|
+
for (const frame of this.__distinct__()) {
|
|
160
|
+
frame.xOffset -= left;
|
|
161
|
+
frame.yOffset -= top;
|
|
135
162
|
}
|
|
136
|
-
this.__canvas__ = [
|
|
163
|
+
this.__canvas__ = [right - left, bottom - top];
|
|
137
164
|
this.frames = this.__clipped_frames__();
|
|
138
165
|
return this;
|
|
139
166
|
}
|
|
@@ -144,7 +171,7 @@ export class Animation {
|
|
|
144
171
|
const [boxWidth, boxHeight] = canvasSize(Math.floor(finite(width, 'width')), Math.floor(finite(height, 'height')));
|
|
145
172
|
this.resize({ width: boxWidth, height: boxHeight, fit: 'inside', ...resizeOpts });
|
|
146
173
|
const x = (boxWidth - this.width) / 2 | 0, y = (boxHeight - this.height) / 2 | 0;
|
|
147
|
-
for (const frame of this.
|
|
174
|
+
for (const frame of this.__distinct__()) {
|
|
148
175
|
frame.xOffset += x;
|
|
149
176
|
frame.yOffset += y;
|
|
150
177
|
}
|
|
@@ -164,10 +191,27 @@ export class Animation {
|
|
|
164
191
|
this.resize(Math.max(boxWidth, Math.round(this.width * scale)), Math.max(boxHeight, Math.round(this.height * scale)), options);
|
|
165
192
|
return this.crop((this.width - boxWidth) / 2, (this.height - boxHeight) / 2, boxWidth, boxHeight);
|
|
166
193
|
}
|
|
194
|
+
flip(direction) {
|
|
195
|
+
oneOf(direction, FLIP_DIRECTIONS, 'flip direction');
|
|
196
|
+
const width = this.width, height = this.height;
|
|
197
|
+
const flipped = new Set();
|
|
198
|
+
for (const frame of this.__distinct__()) {
|
|
199
|
+
if (!flipped.has(frame.image))
|
|
200
|
+
frame.image.flip(direction);
|
|
201
|
+
flipped.add(frame.image);
|
|
202
|
+
if (direction === 'horizontal')
|
|
203
|
+
frame.xOffset = width - frame.xOffset - frame.width;
|
|
204
|
+
else
|
|
205
|
+
frame.yOffset = height - frame.yOffset - frame.height;
|
|
206
|
+
}
|
|
207
|
+
if (width && height)
|
|
208
|
+
this.__canvas__ = [width, height];
|
|
209
|
+
return this;
|
|
210
|
+
}
|
|
167
211
|
scale(factor, options) {
|
|
168
212
|
if (!(finite(factor, 'factor') > 0))
|
|
169
213
|
throw new RangeError(`Invalid scale factor: ${factor}`);
|
|
170
|
-
return this.resize(this.width * factor, this.height * factor, options);
|
|
214
|
+
return this.resize(Math.max(1, this.width * factor), Math.max(1, this.height * factor), options);
|
|
171
215
|
}
|
|
172
216
|
trim(options = {}) {
|
|
173
217
|
checkOptions(options, 'trim({ tolerance: 0.1 })');
|
|
@@ -223,6 +267,9 @@ export class Animation {
|
|
|
223
267
|
this.__canvas__ = [probe.width, probe.height];
|
|
224
268
|
return this;
|
|
225
269
|
}
|
|
270
|
+
__distinct__() {
|
|
271
|
+
return [...new Set(this.__frames__)];
|
|
272
|
+
}
|
|
226
273
|
__clipped_frames__() {
|
|
227
274
|
const width = this.width, height = this.height;
|
|
228
275
|
return this.frames.map(frame => {
|
|
@@ -247,6 +294,13 @@ export class Animation {
|
|
|
247
294
|
throw new Error('Animation contains invalid frames');
|
|
248
295
|
fitDuration(frame.duration, format);
|
|
249
296
|
}
|
|
297
|
+
const { width, height } = this;
|
|
298
|
+
if (width < 1 || height < 1)
|
|
299
|
+
throw new RangeError('The animation has no canvas: every frame lies outside of it');
|
|
300
|
+
if (format === 'GIF' && (width > 0xffff || height > 0xffff))
|
|
301
|
+
throw new RangeError(`GIF: images can be at most 65535 pixels wide and high, not ${width}x${height}`);
|
|
302
|
+
if (format === 'WebP' && (width > 1 << 24 || height > 1 << 24))
|
|
303
|
+
throw new RangeError('WebP: canvas too large');
|
|
250
304
|
}
|
|
251
305
|
async encodeGIF(options = {}) {
|
|
252
306
|
checkOptions(options, 'encodeGIF({ colors: 64 })');
|
|
@@ -343,13 +397,10 @@ export class Animation {
|
|
|
343
397
|
static async decode(input, options = {}) {
|
|
344
398
|
checkOptions(options, 'Animation.decode(data, { maxPixels: 1e8 })');
|
|
345
399
|
const { maxPixels = MAX_PIXELS, threads = 1 } = options;
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
if (!(Number(maxPixels) > 0))
|
|
349
|
-
throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
|
|
400
|
+
checkThreads(threads);
|
|
401
|
+
pixelLimit(maxPixels);
|
|
350
402
|
const { toneMapping = 'reinhard' } = options;
|
|
351
|
-
|
|
352
|
-
throw new TypeError(`toneMapping must be 'reinhard' or 'clamp', not ${String(toneMapping)}`);
|
|
403
|
+
oneOf(toneMapping, TONE_MAPPINGS, 'toneMapping');
|
|
353
404
|
return decoding(() => Animation.__decode__(input, options));
|
|
354
405
|
}
|
|
355
406
|
static __is_animated__(animation) {
|
|
@@ -388,7 +439,10 @@ export class Animation {
|
|
|
388
439
|
}
|
|
389
440
|
if (type === 'png') {
|
|
390
441
|
const decoded = await png.decodeAnimation(data, false, maxPixels);
|
|
391
|
-
const
|
|
442
|
+
const step = png.compositor(decoded.width, decoded.height), shown = [];
|
|
443
|
+
for await (const frame of decoded.frames)
|
|
444
|
+
shown.push({ pixels: step(frame), duration: frame.duration });
|
|
445
|
+
const frames = orient(profile(canvasFrames(decoded.width, decoded.height, shown), decoded.icc), decoded.orientation);
|
|
392
446
|
const animation = new Animation(frames, { loopCount: fromPlays(decoded.plays), width: frames[0]?.width ?? decoded.width, height: frames[0]?.height ?? decoded.height });
|
|
393
447
|
animation.__animationSignal__ = true;
|
|
394
448
|
return animation;
|
|
@@ -401,6 +455,7 @@ export class Animation {
|
|
|
401
455
|
const image = new Image(decoded.width, decoded.height);
|
|
402
456
|
image.bitmap = alignedPixels(decoded.pixels);
|
|
403
457
|
frames.push(new Frame(image, { duration: decoded.duration, disposalMode: 'background' }));
|
|
458
|
+
checkPixels(decoded.width, decoded.height, maxPixels, frames.length);
|
|
404
459
|
orientation = decoded.orientation;
|
|
405
460
|
loops = fromPlays(decoded.loopCount);
|
|
406
461
|
animated ||= decoded.animated;
|
package/dist/codecs/gif.js
CHANGED
|
@@ -5,6 +5,7 @@ const DISPOSAL_TO_GIF = [0, 1, 3, 2];
|
|
|
5
5
|
const DISPOSAL_FROM_GIF = [0, 1, 3, 2, 0, 0, 0, 0];
|
|
6
6
|
const MAX_CODE = 4095;
|
|
7
7
|
const UNEXPECTED_END = new Error('GIF: unexpected end of data');
|
|
8
|
+
const EMPTY = new Uint8Array(0);
|
|
8
9
|
export function encode({ width, height, loopCount = Infinity, frames }, palette, comments = []) {
|
|
9
10
|
const restores = frames.some(frame => frame.dispose === 3);
|
|
10
11
|
const parts = [header(width, height, loopCount, comments)];
|
|
@@ -144,7 +145,7 @@ export function decode(data, firstFrameOnly = false, maxPixels = MAX_PIXELS) {
|
|
|
144
145
|
parse();
|
|
145
146
|
}
|
|
146
147
|
catch (err) {
|
|
147
|
-
if (err !== UNEXPECTED_END)
|
|
148
|
+
if (err !== UNEXPECTED_END || !frames.length)
|
|
148
149
|
throw err;
|
|
149
150
|
}
|
|
150
151
|
checkPixels(width, height, maxPixels, Math.max(1, frames.length));
|
|
@@ -153,7 +154,7 @@ export function decode(data, firstFrameOnly = false, maxPixels = MAX_PIXELS) {
|
|
|
153
154
|
while (reader.offset < data.length) {
|
|
154
155
|
const block = reader.u8();
|
|
155
156
|
if (block === 0x3b)
|
|
156
|
-
|
|
157
|
+
return;
|
|
157
158
|
if (block === 0x21) {
|
|
158
159
|
const label = reader.u8();
|
|
159
160
|
if (label === 0xf9) {
|
|
@@ -189,7 +190,7 @@ export function decode(data, firstFrameOnly = false, maxPixels = MAX_PIXELS) {
|
|
|
189
190
|
}
|
|
190
191
|
if (block !== 0x2c) {
|
|
191
192
|
if (frames.length)
|
|
192
|
-
|
|
193
|
+
return;
|
|
193
194
|
throw new Error(`GIF: unknown block type 0x${block.toString(16)}`);
|
|
194
195
|
}
|
|
195
196
|
const x = reader.u16();
|
|
@@ -223,8 +224,9 @@ export function decode(data, firstFrameOnly = false, maxPixels = MAX_PIXELS) {
|
|
|
223
224
|
}
|
|
224
225
|
frames.push({ x, y, width: fw, height: fh, delay, dispose, indices: ordered, colors, transparentIndex });
|
|
225
226
|
if (firstFrameOnly)
|
|
226
|
-
|
|
227
|
+
return;
|
|
227
228
|
}
|
|
229
|
+
throw UNEXPECTED_END;
|
|
228
230
|
}
|
|
229
231
|
}
|
|
230
232
|
export function composite({ width, height, frames }) {
|
|
@@ -249,6 +251,7 @@ export function composite({ width, height, frames }) {
|
|
|
249
251
|
}
|
|
250
252
|
}
|
|
251
253
|
output.push({ pixels: new Uint8Array(canvas.slice().buffer), delay: frame.delay });
|
|
254
|
+
frame.indices = EMPTY;
|
|
252
255
|
if (frame.dispose === 3) {
|
|
253
256
|
for (let y = y0; y < y1; y++)
|
|
254
257
|
canvas.fill(0, y * width + x0, y * width + x1);
|
|
@@ -333,11 +336,19 @@ function lzwDecode(data, minCodeSize, pixelCount) {
|
|
|
333
336
|
function readSubBlocks(reader) {
|
|
334
337
|
const blocks = [];
|
|
335
338
|
let total = 0;
|
|
336
|
-
|
|
339
|
+
let terminated = false;
|
|
340
|
+
while (reader.offset < reader.data.length) {
|
|
341
|
+
const length = reader.u8();
|
|
342
|
+
if (!length) {
|
|
343
|
+
terminated = true;
|
|
344
|
+
break;
|
|
345
|
+
}
|
|
337
346
|
const block = reader.slice(length);
|
|
338
347
|
blocks.push(block);
|
|
339
348
|
total += block.length;
|
|
340
349
|
}
|
|
350
|
+
if (!terminated)
|
|
351
|
+
throw UNEXPECTED_END;
|
|
341
352
|
const out = new Uint8Array(total);
|
|
342
353
|
let offset = 0;
|
|
343
354
|
for (const block of blocks) {
|
package/dist/codecs/jpeg.js
CHANGED
|
@@ -86,6 +86,8 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
|
|
|
86
86
|
case 0xc2: {
|
|
87
87
|
if (frame)
|
|
88
88
|
throw new Error('JPEG: multiple frames are not supported');
|
|
89
|
+
if (end - start < 6)
|
|
90
|
+
throw new Error('JPEG: truncated frame header');
|
|
89
91
|
if (data[start] !== 8)
|
|
90
92
|
throw new Error(`JPEG: ${data[start]}-bit precision is not supported`);
|
|
91
93
|
checkPixels(u16(start + 3), u16(start + 1), maxPixels);
|