imagescript 4.0.0-rc.3 → 4.0.0-rc.5
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 +13 -1
- package/dist/animation-encoder.d.ts +13 -6
- package/dist/animation-encoder.js +17 -8
- package/dist/animation.d.ts +55 -9
- package/dist/animation.js +71 -21
- package/dist/codecs/bmp.js +1 -1
- package/dist/codecs/gif.js +16 -5
- package/dist/codecs/jpeg.js +40 -7
- package/dist/codecs/jxl/frame.js +4 -1
- package/dist/codecs/jxl/vardct-enc.js +2 -1
- package/dist/codecs/png.js +52 -22
- package/dist/codecs/quantize.js +3 -5
- package/dist/codecs/tiff.js +8 -1
- package/dist/codecs/vp8.js +1 -1
- package/dist/codecs/webp.js +25 -21
- package/dist/colors.d.ts +3 -0
- package/dist/colors.js +30 -18
- package/dist/frame.d.ts +18 -5
- package/dist/frame.js +2 -0
- package/dist/gainmap.d.ts +41 -15
- package/dist/gainmap.js +19 -10
- package/dist/image.d.ts +379 -123
- package/dist/image.js +100 -58
- package/dist/metadata.d.ts +11 -2
- package/dist/metadata.js +11 -4
- package/dist/package.json +1 -1
- package/dist/render/svg.js +138 -50
- package/dist/render/text.js +12 -7
- package/dist/text-layout.d.ts +12 -5
- package/dist/text-layout.js +6 -5
- package/dist/util/inspect.js +16 -0
- package/dist/util/limits.d.ts +5 -0
- package/dist/util/limits.js +4 -0
- package/dist/util/mem.js +1 -1
- package/dist/util/options.js +71 -9
- 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 (TypeScript 5.7 or newer
|
|
19
|
+
definitions (TypeScript 5.7 or newer; CommonJS projects with `module: nodenext` need 5.8 or newer to `import` it. 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, `bun build`) 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
|
|
@@ -81,6 +90,9 @@ and encoded as GIF, APNG or WebP, all at once or
|
|
|
81
90
|
[frame by frame](https://imagescript.dev/classes/Animation.html#webpencoder). Lossless encoding keeps every pixel
|
|
82
91
|
exactly; lossy encoding makes smaller files by approximating some image detail.
|
|
83
92
|
|
|
93
|
+
Not supported (decoding them throws an error): CCITT-compressed TIFF and arithmetic-coded JPEG. Lossless JPEG XL is
|
|
94
|
+
fast but not small: for small lossless files, PNG or WebP are the better choice.
|
|
95
|
+
|
|
84
96
|
Embedded color profiles are converted to sRGB, the standard color format for most screens, where supported. CMYK and
|
|
85
97
|
lookup-table profiles are left unchanged.
|
|
86
98
|
|
|
@@ -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;
|
|
@@ -26,8 +27,14 @@ export declare class AnimationEncoder {
|
|
|
26
27
|
* default). The options override the frame's. The pixels are copied right away, the image can change afterwards
|
|
27
28
|
* @param frame The frame or image
|
|
28
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
|
|
29
33
|
*/
|
|
30
34
|
add(frame: Frame | Image, options?: FrameOptions): Promise<void>;
|
|
31
|
-
/**
|
|
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
|
+
*/
|
|
32
39
|
finish(): Promise<Uint8Array<ArrayBuffer>>;
|
|
33
40
|
}
|
|
@@ -7,7 +7,7 @@ import { Frame } from "./frame.js";
|
|
|
7
7
|
import { Optimizer, Compositor, coverCanvas, fillUnchanged } from "./util/optimize.js";
|
|
8
8
|
import { compressAsync, decompressAsync } from "./codecs/zlib.js";
|
|
9
9
|
import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
|
|
10
|
-
import { checkOptions, finite, compressionLevel, loopCount, toPlays, fitLoops, fitDuration, maxDuration } from "./util/options.js";
|
|
10
|
+
import { checkOptions, finite, compressionLevel, loopCount, toPlays, fitLoops, fitDuration, maxDuration, boolean } from "./util/options.js";
|
|
11
11
|
function clipToCanvas(frame, width, height) {
|
|
12
12
|
const { x, y, width: w, height: h } = frame;
|
|
13
13
|
if (x >= 0 && y >= 0 && x + w <= width && y + h <= height)
|
|
@@ -30,6 +30,8 @@ export class AnimationEncoder {
|
|
|
30
30
|
height;
|
|
31
31
|
constructor(width, height, format, optimize) {
|
|
32
32
|
this.format = format;
|
|
33
|
+
if (!format)
|
|
34
|
+
throw new TypeError('AnimationEncoder is created by Animation.gifEncoder(), apngEncoder() or webpEncoder()');
|
|
33
35
|
this.width = width;
|
|
34
36
|
this.height = height;
|
|
35
37
|
this.optimizer = optimize ? new Optimizer(width, height, format.optimize) : null;
|
|
@@ -45,12 +47,12 @@ export class AnimationEncoder {
|
|
|
45
47
|
const image = own ? own.image : frame;
|
|
46
48
|
if (!(image instanceof Image))
|
|
47
49
|
throw new TypeError('encoder.add() takes a Frame or an Image');
|
|
48
|
-
const duration = finite(options.duration
|
|
50
|
+
const duration = finite(options.duration === undefined ? own?.duration ?? 100 : options.duration, 'frame duration');
|
|
49
51
|
if (duration < 0)
|
|
50
52
|
throw new RangeError('Invalid frame duration');
|
|
51
53
|
fitDuration(duration, this.format.name);
|
|
52
|
-
const x = Math.trunc(finite(options.xOffset
|
|
53
|
-
const y = Math.trunc(finite(options.yOffset
|
|
54
|
+
const x = Math.trunc(finite(options.xOffset === undefined ? own?.xOffset ?? 0 : options.xOffset, 'x offset')) || 0;
|
|
55
|
+
const y = Math.trunc(finite(options.yOffset === undefined ? own?.yOffset ?? 0 : options.yOffset, 'y offset')) || 0;
|
|
54
56
|
const disposal = options.disposalMode !== undefined ? Frame.__convert_disposal_mode__(options.disposalMode) : own ? own.__disposal_id__ : 1;
|
|
55
57
|
const input = {
|
|
56
58
|
x, y, width: image.width, height: image.height, duration, disposal,
|
|
@@ -82,8 +84,9 @@ export class AnimationEncoder {
|
|
|
82
84
|
return this.format.file(optimizer);
|
|
83
85
|
}
|
|
84
86
|
static __webp__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 }) {
|
|
87
|
+
boolean(optimize, 'optimize');
|
|
85
88
|
const loops = fitLoops(loopCount(count), 'WebP');
|
|
86
|
-
canvas(width, height);
|
|
89
|
+
canvas(width, height, 'WebP');
|
|
87
90
|
if (width > 1 << 24 || height > 1 << 24)
|
|
88
91
|
throw new RangeError('WebP: canvas too large');
|
|
89
92
|
const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
|
|
@@ -114,8 +117,9 @@ export class AnimationEncoder {
|
|
|
114
117
|
static __gif__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85 }) {
|
|
115
118
|
const checked = paletteOptions(colors, dither, ditherStrength);
|
|
116
119
|
const palette = { colors: checked.colors, dither: checked.dither, strength: checked.strength };
|
|
120
|
+
boolean(optimize, 'optimize');
|
|
117
121
|
const loops = fitLoops(loopCount(count), 'GIF');
|
|
118
|
-
canvas(width, height);
|
|
122
|
+
canvas(width, height, 'GIF');
|
|
119
123
|
const comments = gifComments(resolveMetadata(metadata));
|
|
120
124
|
let first = null, restores = false;
|
|
121
125
|
const rest = [];
|
|
@@ -142,8 +146,9 @@ export class AnimationEncoder {
|
|
|
142
146
|
}
|
|
143
147
|
static __apng__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, compression: compressionOption = 4 }) {
|
|
144
148
|
const compression = compressionLevel(compressionOption);
|
|
149
|
+
boolean(optimize, 'optimize');
|
|
145
150
|
const loops = fitLoops(loopCount(count), 'APNG');
|
|
146
|
-
canvas(width, height);
|
|
151
|
+
canvas(width, height, 'APNG');
|
|
147
152
|
const text = pngText(resolveMetadata(metadata));
|
|
148
153
|
const stored = [];
|
|
149
154
|
const cost = new png.AlphaCost();
|
|
@@ -190,9 +195,13 @@ export class AnimationEncoder {
|
|
|
190
195
|
}, optimize);
|
|
191
196
|
}
|
|
192
197
|
}
|
|
193
|
-
function canvas(width, height) {
|
|
198
|
+
function canvas(width, height, format) {
|
|
199
|
+
finite(width, 'width');
|
|
200
|
+
finite(height, 'height');
|
|
194
201
|
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1)
|
|
195
202
|
throw new RangeError(`Invalid canvas size: ${width}x${height}`);
|
|
203
|
+
if (format === 'GIF' && (width > 0xffff || height > 0xffff))
|
|
204
|
+
throw new RangeError(`GIF: images can be at most 65535 pixels wide and high, not ${width}x${height}`);
|
|
196
205
|
}
|
|
197
206
|
function webpFrame(f) {
|
|
198
207
|
let { x, y, width: w, height: h, pixels } = f;
|
package/dist/animation.d.ts
CHANGED
|
@@ -6,19 +6,23 @@ import { AnimationEncoder } from './animation-encoder.js';
|
|
|
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,7 +30,10 @@ 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
|
}
|
|
@@ -56,6 +63,14 @@ export interface APNGEncodeOptions extends PNGEncodeOptions, AnimationEncodeOpti
|
|
|
56
63
|
export declare class Animation {
|
|
57
64
|
/**
|
|
58
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
|
+
* ```
|
|
59
74
|
* @param frames The frames to create the animation from
|
|
60
75
|
* @param options The canvas size and the loop count, see {@link AnimationCanvasOptions}
|
|
61
76
|
*/
|
|
@@ -101,9 +116,13 @@ export declare class Animation {
|
|
|
101
116
|
/**
|
|
102
117
|
* Resizes the animation to the given dimensions, scaling every frame and its offsets proportionally.
|
|
103
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)
|
|
104
122
|
* @param width The new width
|
|
105
123
|
* @param height The new height
|
|
106
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
|
|
107
126
|
*/
|
|
108
127
|
resize(width: number, height: number, options?: ResizeOptions): this;
|
|
109
128
|
/**
|
|
@@ -173,7 +192,11 @@ export declare class Animation {
|
|
|
173
192
|
* before and merges identical frames (unless the `optimize` option is false), so the file decodes to what the
|
|
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
|
-
* @param options See {@link GIFAnimationEncodeOptions}
|
|
195
|
+
* @param options See {@link GIFAnimationEncodeOptions}; the loop count is the animation's {@link loopCount} (the
|
|
196
|
+
* streaming {@link gifEncoder} takes it as an option)
|
|
197
|
+
* @throws `Error` if the animation has no frames
|
|
198
|
+
* @throws `RangeError` if the loop count or a frame's duration is more than GIF stores, or the canvas is wider or
|
|
199
|
+
* higher than 65535 pixels
|
|
177
200
|
*/
|
|
178
201
|
encodeGIF(options?: GIFAnimationEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
|
|
179
202
|
/**
|
|
@@ -181,20 +204,33 @@ export declare class Animation {
|
|
|
181
204
|
* the first frame. Each frame is stored as the area that changed since the frame before, identical frames are
|
|
182
205
|
* merged (unless the `optimize` option is false): the file shows exactly the same animation, but doesn't
|
|
183
206
|
* necessarily decode to the same frames
|
|
184
|
-
* @param options See {@link APNGEncodeOptions}
|
|
207
|
+
* @param options See {@link APNGEncodeOptions}; the loop count is the animation's {@link loopCount} (the streaming
|
|
208
|
+
* {@link apngEncoder} takes it as an option)
|
|
209
|
+
* @throws `Error` if the animation has no frames
|
|
210
|
+
* @throws `RangeError` if the loop count or a frame's duration is more than APNG stores
|
|
185
211
|
*/
|
|
186
212
|
encodeAPNG(options?: APNGEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
|
|
187
213
|
/**
|
|
188
214
|
* Encodes the animation as animated WebP, lossless or (with a quality) lossy. Each frame is stored as the area that
|
|
189
215
|
* changed since the frame before, identical frames are merged (unless the `optimize` option is false): the file
|
|
190
216
|
* shows the same animation, but doesn't necessarily decode to the same frames
|
|
191
|
-
* @param options See {@link WebPAnimationEncodeOptions}
|
|
217
|
+
* @param options See {@link WebPAnimationEncodeOptions}; the loop count is the animation's {@link loopCount} (the
|
|
218
|
+
* streaming {@link webpEncoder} takes it as an option)
|
|
219
|
+
* @throws `Error` if the animation has no frames
|
|
220
|
+
* @throws `RangeError` if the loop count or a frame's duration is more than WebP stores
|
|
192
221
|
*/
|
|
193
222
|
encodeWebP(options?: WebPAnimationEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
|
|
194
223
|
/**
|
|
195
224
|
* An encoder that makes an animated WebP a frame at a time, like {@link Animation.encodeWebP} (the same file),
|
|
196
225
|
* without keeping the frames in memory: `await encoder.add(frame)` for each frame (a {@link Frame}, or an image
|
|
197
226
|
* with `{ duration }`), then `await encoder.finish()` for the file
|
|
227
|
+
* @example
|
|
228
|
+
* ```ts
|
|
229
|
+
* const encoder = Animation.webpEncoder(64, 64, { quality: 80 });
|
|
230
|
+
* for (const color of [0xff0000ff, 0x00ff00ff, 0x0000ffff])
|
|
231
|
+
* await encoder.add(new Image(64, 64).fill(color), { duration: 200 });
|
|
232
|
+
* const webp = await encoder.finish();
|
|
233
|
+
* ```
|
|
198
234
|
* @param width The canvas width
|
|
199
235
|
* @param height The canvas height
|
|
200
236
|
* @param options See {@link WebPAnimationEncodeOptions}, and {@link AnimationOptions.loopCount}
|
|
@@ -219,8 +255,18 @@ export declare class Animation {
|
|
|
219
255
|
static apngEncoder(width: number, height: number, options?: APNGEncodeOptions & AnimationOptions): AnimationEncoder;
|
|
220
256
|
/**
|
|
221
257
|
* Decodes an animated GIF, APNG, WebP or JPEG XL into fully composited frames (still images become a single frame)
|
|
258
|
+
* @example
|
|
259
|
+
* ```ts
|
|
260
|
+
* const animation = await Animation.decode(gifBytes);
|
|
261
|
+
* const webp = await animation.resize({ width: 320 }).encodeWebP({ quality: 75 });
|
|
262
|
+
* ```
|
|
263
|
+
* @remarks A still image becomes one frame of 100 ms, the {@link Frame} default. An AVIF image sequence is decoded as
|
|
264
|
+
* its first frame only. A file that is cut off keeps the frames that arrived whole (like browsers show it) and
|
|
265
|
+
* throws when not even the first one did
|
|
222
266
|
* @param input The binary data to decode
|
|
223
267
|
* @param options See {@link DecodeOptions}
|
|
268
|
+
* @throws {@link LimitError} if the frames have more than `options.maxPixels` pixels together
|
|
269
|
+
* @throws `Error` if the data isn't a supported image, or is damaged or cut off before its first whole frame
|
|
224
270
|
*/
|
|
225
271
|
static decode(input: BinaryData, options?: DecodeOptions): Promise<Animation>;
|
|
226
272
|
}
|
package/dist/animation.js
CHANGED
|
@@ -12,9 +12,10 @@ 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, oneOf, pixelLimit, checkThreads, 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, boolean, 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
|
+
import { describe } from "./util/inspect.js";
|
|
18
19
|
function canvasFrames(width, height, frames) {
|
|
19
20
|
return frames.map(({ pixels, duration }) => {
|
|
20
21
|
const image = new Image(width, height);
|
|
@@ -49,6 +50,8 @@ export class Animation {
|
|
|
49
50
|
return this.__framesView__ ??= Object.freeze([...this.__frames__]);
|
|
50
51
|
}
|
|
51
52
|
set frames(frames) {
|
|
53
|
+
if (frames === null || typeof frames !== 'object' || typeof frames[Symbol.iterator] !== 'function')
|
|
54
|
+
throw new TypeError(`Animation() takes an array of Frame objects, not ${frames === null ? 'null' : typeof frames}`);
|
|
52
55
|
const copy = [];
|
|
53
56
|
for (const frame of frames) {
|
|
54
57
|
if (!(frame instanceof Frame))
|
|
@@ -106,22 +109,44 @@ export class Animation {
|
|
|
106
109
|
const originalWidth = this.width, originalHeight = this.height;
|
|
107
110
|
if (!originalWidth || !originalHeight)
|
|
108
111
|
throw new RangeError('An animation without frames or canvas can\'t be resized');
|
|
109
|
-
|
|
110
|
-
|
|
112
|
+
if (givenWidth !== undefined && Math.floor(givenWidth) < 1)
|
|
113
|
+
throw new RangeError('The animation has to be at least 1 pixel wide');
|
|
114
|
+
if (givenHeight !== undefined && Math.floor(givenHeight) < 1)
|
|
115
|
+
throw new RangeError('The animation has to be at least 1 pixel high');
|
|
116
|
+
let width, height;
|
|
111
117
|
if (fit === 'inside' && givenWidth !== undefined && givenHeight !== undefined)
|
|
112
|
-
[width, height] = insideSize(originalWidth, originalHeight, givenWidth, givenHeight);
|
|
113
|
-
|
|
118
|
+
[width, height] = insideSize(originalWidth, originalHeight, givenWidth, givenHeight).map(Math.floor);
|
|
119
|
+
else if (givenWidth === undefined) {
|
|
120
|
+
height = Math.floor(givenHeight);
|
|
121
|
+
width = Math.max(1, Math.round(originalWidth / originalHeight * height));
|
|
122
|
+
}
|
|
123
|
+
else if (givenHeight === undefined) {
|
|
124
|
+
width = Math.floor(givenWidth);
|
|
125
|
+
height = Math.max(1, Math.round(originalHeight / originalWidth * width));
|
|
126
|
+
}
|
|
127
|
+
else
|
|
128
|
+
[width, height] = [Math.floor(givenWidth), Math.floor(givenHeight)];
|
|
129
|
+
const canvas = canvasSize(Math.max(1, width), Math.max(1, height));
|
|
114
130
|
const sx = width / originalWidth, sy = height / originalHeight;
|
|
115
131
|
const changes = this.__distinct__().map(frame => {
|
|
116
132
|
const left = Math.round(frame.xOffset * sx), top = Math.round(frame.yOffset * sy);
|
|
117
133
|
const right = Math.round((frame.xOffset + frame.width) * sx), bottom = Math.round((frame.yOffset + frame.height) * sy);
|
|
118
134
|
return { frame, left, top, width: Math.max(1, right - left), height: Math.max(1, bottom - top) };
|
|
119
135
|
});
|
|
120
|
-
const
|
|
136
|
+
const shared = new Set(), seen = new Set();
|
|
137
|
+
for (const { frame } of changes)
|
|
138
|
+
(seen.has(frame.image) ? shared : seen).add(frame.image);
|
|
139
|
+
const originals = new Map(Array.from(shared, image => [image, image.clone()]));
|
|
140
|
+
const resized = new Map();
|
|
121
141
|
for (const { frame, left, top, width, height } of changes) {
|
|
122
|
-
|
|
142
|
+
const size = `${width}x${height}`, done = resized.get(frame.image), original = originals.get(frame.image);
|
|
143
|
+
if (done === undefined) {
|
|
144
|
+
resized.set(frame.image, size);
|
|
123
145
|
frame.image.resize(width, height, options);
|
|
124
|
-
|
|
146
|
+
}
|
|
147
|
+
else if (done !== size && original) {
|
|
148
|
+
frame.image = original.clone().resize(width, height, options);
|
|
149
|
+
}
|
|
125
150
|
frame.xOffset = left;
|
|
126
151
|
frame.yOffset = top;
|
|
127
152
|
}
|
|
@@ -129,17 +154,16 @@ export class Animation {
|
|
|
129
154
|
return this;
|
|
130
155
|
}
|
|
131
156
|
crop(x, y, width, height) {
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
if (!(width >= 1 && height >= 1))
|
|
157
|
+
const left = Math.max(0, Math.floor(finite(x, 'x'))), top = Math.max(0, Math.floor(finite(y, 'y')));
|
|
158
|
+
const right = Math.min(this.width, Math.floor(finite(x, 'x')) + Math.floor(finite(width, 'width')));
|
|
159
|
+
const bottom = Math.min(this.height, Math.floor(finite(y, 'y')) + Math.floor(finite(height, 'height')));
|
|
160
|
+
if (!(right - left >= 1 && bottom - top >= 1))
|
|
137
161
|
throw new RangeError('The crop region has to overlap the canvas');
|
|
138
162
|
for (const frame of this.__distinct__()) {
|
|
139
|
-
frame.xOffset -=
|
|
140
|
-
frame.yOffset -=
|
|
163
|
+
frame.xOffset -= left;
|
|
164
|
+
frame.yOffset -= top;
|
|
141
165
|
}
|
|
142
|
-
this.__canvas__ = [
|
|
166
|
+
this.__canvas__ = [right - left, bottom - top];
|
|
143
167
|
this.frames = this.__clipped_frames__();
|
|
144
168
|
return this;
|
|
145
169
|
}
|
|
@@ -190,7 +214,7 @@ export class Animation {
|
|
|
190
214
|
scale(factor, options) {
|
|
191
215
|
if (!(finite(factor, 'factor') > 0))
|
|
192
216
|
throw new RangeError(`Invalid scale factor: ${factor}`);
|
|
193
|
-
return this.resize(this.width * factor, this.height * factor, options);
|
|
217
|
+
return this.resize(Math.max(1, this.width * factor), Math.max(1, this.height * factor), options);
|
|
194
218
|
}
|
|
195
219
|
trim(options = {}) {
|
|
196
220
|
checkOptions(options, 'trim({ tolerance: 0.1 })');
|
|
@@ -273,10 +297,18 @@ export class Animation {
|
|
|
273
297
|
throw new Error('Animation contains invalid frames');
|
|
274
298
|
fitDuration(frame.duration, format);
|
|
275
299
|
}
|
|
300
|
+
const { width, height } = this;
|
|
301
|
+
if (width < 1 || height < 1)
|
|
302
|
+
throw new RangeError('The animation has no canvas: every frame lies outside of it');
|
|
303
|
+
if (format === 'GIF' && (width > 0xffff || height > 0xffff))
|
|
304
|
+
throw new RangeError(`GIF: images can be at most 65535 pixels wide and high, not ${width}x${height}`);
|
|
305
|
+
if (format === 'WebP' && (width > 1 << 24 || height > 1 << 24))
|
|
306
|
+
throw new RangeError('WebP: canvas too large');
|
|
276
307
|
}
|
|
277
308
|
async encodeGIF(options = {}) {
|
|
278
309
|
checkOptions(options, 'encodeGIF({ colors: 64 })');
|
|
279
310
|
const { colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85, metadata = {}, optimize = true } = options;
|
|
311
|
+
boolean(optimize, 'optimize');
|
|
280
312
|
const palette = paletteOptions(colors, dither, ditherStrength);
|
|
281
313
|
const loops = fitLoops(this.loopCount, 'GIF');
|
|
282
314
|
this.__validate__('GIF');
|
|
@@ -297,6 +329,7 @@ export class Animation {
|
|
|
297
329
|
async encodeAPNG(options = {}) {
|
|
298
330
|
checkOptions(options, 'encodeAPNG({ compression: 9 })');
|
|
299
331
|
const { compression = 4, metadata = {}, optimize = true } = options;
|
|
332
|
+
boolean(optimize, 'optimize');
|
|
300
333
|
const loops = fitLoops(this.loopCount, 'APNG');
|
|
301
334
|
this.__validate__('APNG');
|
|
302
335
|
const frames = optimize
|
|
@@ -307,6 +340,7 @@ export class Animation {
|
|
|
307
340
|
async encodeWebP(options = {}) {
|
|
308
341
|
checkOptions(options, 'animation.encodeWebP({ quality: 80 })');
|
|
309
342
|
const { metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 } = options;
|
|
343
|
+
boolean(optimize, 'optimize');
|
|
310
344
|
const loops = fitLoops(this.loopCount, 'WebP');
|
|
311
345
|
this.__validate__('WebP');
|
|
312
346
|
const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
|
|
@@ -380,6 +414,9 @@ export class Animation {
|
|
|
380
414
|
}
|
|
381
415
|
static async __decode__(input, options) {
|
|
382
416
|
const { maxPixels = MAX_PIXELS, applyColorProfile = true, threads = Math.max(1, Math.min(availableThreads(), 8)), applyOrientation = true, toneMapping = 'reinhard', gainMap = true } = options;
|
|
417
|
+
boolean(applyOrientation, 'applyOrientation');
|
|
418
|
+
boolean(applyColorProfile, 'applyColorProfile');
|
|
419
|
+
boolean(gainMap, 'gainMap');
|
|
383
420
|
const orient = (frames, orientation) => {
|
|
384
421
|
if (applyOrientation && orientation > 1)
|
|
385
422
|
for (const frame of frames)
|
|
@@ -403,15 +440,21 @@ export class Animation {
|
|
|
403
440
|
const frames = orient(profile(canvasFrames(decoded.width, decoded.height, webp.composite(decoded)), decoded.icc), decoded.orientation);
|
|
404
441
|
const animation = new Animation(frames, { loopCount: fromPlays(decoded.loopCount), width: frames[0]?.width ?? decoded.width, height: frames[0]?.height ?? decoded.height });
|
|
405
442
|
animation.__animationSignal__ = animated;
|
|
443
|
+
if (!animated)
|
|
444
|
+
for (const frame of frames)
|
|
445
|
+
frame.duration = 100;
|
|
406
446
|
return animation;
|
|
407
447
|
}
|
|
408
448
|
if (type === 'png' && !png.isAnimated(data)) {
|
|
409
449
|
const image = await Image.decode(data, { maxPixels, applyOrientation, applyColorProfile });
|
|
410
|
-
return new Animation(canvasFrames(image.width, image.height, [{ pixels: image.bitmap, duration:
|
|
450
|
+
return new Animation(canvasFrames(image.width, image.height, [{ pixels: image.bitmap, duration: 100 }]), { loopCount: Infinity, width: image.width, height: image.height });
|
|
411
451
|
}
|
|
412
452
|
if (type === 'png') {
|
|
413
453
|
const decoded = await png.decodeAnimation(data, false, maxPixels);
|
|
414
|
-
const
|
|
454
|
+
const step = png.compositor(decoded.width, decoded.height), shown = [];
|
|
455
|
+
for await (const frame of decoded.frames)
|
|
456
|
+
shown.push({ pixels: step(frame), duration: frame.duration });
|
|
457
|
+
const frames = orient(profile(canvasFrames(decoded.width, decoded.height, shown), decoded.icc), decoded.orientation);
|
|
415
458
|
const animation = new Animation(frames, { loopCount: fromPlays(decoded.plays), width: frames[0]?.width ?? decoded.width, height: frames[0]?.height ?? decoded.height });
|
|
416
459
|
animation.__animationSignal__ = true;
|
|
417
460
|
return animation;
|
|
@@ -424,6 +467,7 @@ export class Animation {
|
|
|
424
467
|
const image = new Image(decoded.width, decoded.height);
|
|
425
468
|
image.bitmap = alignedPixels(decoded.pixels);
|
|
426
469
|
frames.push(new Frame(image, { duration: decoded.duration, disposalMode: 'background' }));
|
|
470
|
+
checkPixels(decoded.width, decoded.height, maxPixels, frames.length);
|
|
427
471
|
orientation = decoded.orientation;
|
|
428
472
|
loops = fromPlays(decoded.loopCount);
|
|
429
473
|
animated ||= decoded.animated;
|
|
@@ -450,11 +494,14 @@ export class Animation {
|
|
|
450
494
|
}
|
|
451
495
|
const animation = new Animation(frames, { loopCount: animated ? loops : Infinity, ...(frames.length ? { width: frames[0].width, height: frames[0].height } : {}) });
|
|
452
496
|
animation.__animationSignal__ = animated;
|
|
497
|
+
if (!animated)
|
|
498
|
+
for (const frame of frames)
|
|
499
|
+
frame.duration = 100;
|
|
453
500
|
return animation;
|
|
454
501
|
}
|
|
455
502
|
if (type) {
|
|
456
503
|
const image = await Image.decode(data, { maxPixels, applyOrientation, applyColorProfile, toneMapping, gainMap, threads });
|
|
457
|
-
return new Animation([new Frame(image
|
|
504
|
+
return new Animation([new Frame(image)], { width: image.width, height: image.height });
|
|
458
505
|
}
|
|
459
506
|
throw new Error('Unsupported image type');
|
|
460
507
|
}
|
|
@@ -467,7 +514,10 @@ export class Animation {
|
|
|
467
514
|
}
|
|
468
515
|
}
|
|
469
516
|
function canvasSize(width, height) {
|
|
517
|
+
finite(width, 'width');
|
|
518
|
+
finite(height, 'height');
|
|
470
519
|
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1)
|
|
471
520
|
throw new RangeError(`Invalid canvas size: ${width}x${height}`);
|
|
472
521
|
return [width, height];
|
|
473
522
|
}
|
|
523
|
+
describe(Animation, animation => ({ width: animation.width, height: animation.height, duration: animation.duration, frames: animation.frames.length }));
|
package/dist/codecs/bmp.js
CHANGED
|
@@ -161,7 +161,7 @@ export function decodeDIB(d, o, pixelOffset, maxPixels, ico = false) {
|
|
|
161
161
|
: (a << 24 | sample(cb, v) << 16 | sample(cg, v) << 8 | sample(cr, v)) >>> 0;
|
|
162
162
|
}
|
|
163
163
|
}
|
|
164
|
-
if (ca.max && !alphaSeen)
|
|
164
|
+
if (ca.max && !alphaSeen && !info.masks)
|
|
165
165
|
for (let i = 0; i < out.length; i++)
|
|
166
166
|
out[i] |= 0xff000000;
|
|
167
167
|
if (ico && bits === 32 && alphaSeen)
|
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) {
|