imagescript 3.20.3 → 4.0.0-rc.2

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.
Files changed (55) hide show
  1. package/LICENSE +16 -12
  2. package/README.md +21 -12
  3. package/THIRD_PARTY_NOTICES.md +1 -1
  4. package/dist/animation-encoder.d.ts +1 -34
  5. package/dist/animation-encoder.js +35 -34
  6. package/dist/animation.d.ts +108 -122
  7. package/dist/animation.js +285 -121
  8. package/dist/codecs/av1/decode.js +1 -1
  9. package/dist/codecs/av1/encode.js +1 -1
  10. package/dist/codecs/gif.js +11 -9
  11. package/dist/codecs/hdr.d.ts +1 -1
  12. package/dist/codecs/jpeg.js +13 -13
  13. package/dist/codecs/jxl/headers.js +3 -3
  14. package/dist/codecs/jxl/patches-enc.js +1 -1
  15. package/dist/codecs/jxl.js +5 -5
  16. package/dist/codecs/netpbm.js +7 -7
  17. package/dist/codecs/png.js +15 -15
  18. package/dist/codecs/quantize.js +34 -8
  19. package/dist/codecs/tiff.js +1 -1
  20. package/dist/codecs/webp.js +3 -3
  21. package/dist/codecs/zlib.js +1 -1
  22. package/dist/colors.d.ts +8 -7
  23. package/dist/colors.js +23 -3
  24. package/dist/frame.d.ts +94 -100
  25. package/dist/frame.js +89 -65
  26. package/dist/gainmap.d.ts +88 -46
  27. package/dist/gainmap.js +75 -51
  28. package/dist/image-type.d.ts +6 -1
  29. package/dist/image-type.js +4 -1
  30. package/dist/image.d.ts +317 -738
  31. package/dist/image.js +308 -438
  32. package/dist/index.d.ts +19 -25
  33. package/dist/index.js +15 -14
  34. package/dist/metadata.d.ts +4 -3
  35. package/dist/metadata.js +9 -7
  36. package/dist/render/colr.js +1 -1
  37. package/dist/render/font.js +1 -1
  38. package/dist/render/layout.js +1 -1
  39. package/dist/render/segment.js +1 -1
  40. package/dist/render/shapers/hangul.js +1 -1
  41. package/dist/render/svg.js +68 -20
  42. package/dist/render/text.js +7 -9
  43. package/dist/text-layout.d.ts +5 -35
  44. package/dist/text-layout.js +11 -12
  45. package/dist/util/gain.js +12 -12
  46. package/dist/util/mem.d.ts +1 -1
  47. package/dist/util/optimize.js +3 -1
  48. package/dist/util/options.js +46 -7
  49. package/package.json +15 -10
  50. package/LICENSE.AGPL-3.0 +0 -619
  51. package/LICENSE.MIT +0 -19
  52. package/dist/gif.d.ts +0 -36
  53. package/dist/gif.js +0 -22
  54. package/dist/util/rotate.js +0 -43
  55. package/dist/version.js +0 -1
package/LICENSE CHANGED
@@ -1,15 +1,19 @@
1
- This software is licensed under the following license(s):
2
- - GNU AFFERO GENERAL PUBLIC LICENSE, Version 3
3
- - MIT License
1
+ Copyright (c) 2020-2026 Mathis Mensing
4
2
 
5
- == SPDX-License-Identifier: AGPL-3.0-or-later OR MIT ==
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
6
9
 
7
- You may choose to comply with either one of the above
8
- mentioned licenses, but a license must be chosen.
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
9
12
 
10
- The corresponding license files can be found in the projects
11
- root directory, prefixed with LICENSE, suffixed with their
12
- corresponding SPDX identifier.
13
-
14
- Parts of this software are derived from third party projects under their
15
- own licenses (MIT, Apache-2.0 and the IJG license), see THIRD_PARTY_NOTICES.md.
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
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://github.com/imagescript/ImageScript/blob/v4/guides/Migrating%20to%204.0.md) 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,6 +1,6 @@
1
1
  # Third party notices
2
2
 
3
- ImageScript is licensed under AGPL-3.0-or-later OR MIT (see [LICENSE](LICENSE)). Parts of it are derived from the
3
+ ImageScript is licensed under MIT (see [LICENSE](LICENSE)). Parts of it are derived from the
4
4
  following projects, under their own licenses. Each derived file says so in its header.
5
5
 
6
6
  | Project | Used in | License |
@@ -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, fitLoops } from "./util/options.js";
10
- const toPlays = (loopCount) => loopCount < 0 || loopCount === Infinity ? 0 : loopCount + 1;
10
+ import { checkOptions, finite, compressionLevel, loopCount, toPlays, fitLoops, fitDuration, maxDuration } from "./util/options.js";
11
11
  export class AnimationEncoder {
12
12
  format;
13
13
  optimizer;
@@ -25,26 +25,25 @@ 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;
37
- const duration = options.duration ?? own?.duration ?? 100;
38
- const x = options.xOffset ?? own?.xOffset ?? 0, y = options.yOffset ?? own?.yOffset ?? 0;
39
- if (finite(duration, 'frame duration') < 0)
33
+ const image = own ? own.image : frame;
34
+ if (!(image instanceof Image))
35
+ throw new TypeError('encoder.add() takes a Frame or an Image');
36
+ const duration = finite(options.duration ?? own?.duration ?? 100, 'frame duration');
37
+ if (duration < 0)
40
38
  throw new RangeError('Invalid frame duration');
41
- finite(x, 'x offset');
42
- finite(y, 'y offset');
39
+ fitDuration(duration, this.format.name);
40
+ const x = Math.trunc(finite(options.xOffset ?? own?.xOffset ?? 0, 'x offset')) || 0;
41
+ const y = Math.trunc(finite(options.yOffset ?? own?.yOffset ?? 0, 'y offset')) || 0;
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,9 +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);
74
- fitLoops(loopCount, 'WebP');
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);
75
74
  if (width > 1 << 24 || height > 1 << 24)
76
75
  throw new RangeError('WebP: canvas too large');
77
76
  const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
@@ -84,7 +83,8 @@ export class AnimationEncoder {
84
83
  chunks.push(await webp.frameChunk(f, lossy, effort));
85
84
  };
86
85
  return new AnimationEncoder(width, height, {
87
- optimize: { replace: true, even: true, alpha: 'frame', tolerance: lossy ? webp.lossyTolerance(lossy.quality) : undefined },
86
+ name: 'WebP',
87
+ optimize: { replace: true, even: true, alpha: 'frame', tolerance: lossy ? webp.lossyTolerance(lossy.quality) : undefined, maxDuration: maxDuration('WebP') },
88
88
  async frame(f, optimized) {
89
89
  if (optimized)
90
90
  return add(f);
@@ -95,18 +95,20 @@ export class AnimationEncoder {
95
95
  return add({ x: 0, y: 0, width, height, duration: input.duration, dispose: true, blend: false, pixels: shown });
96
96
  await add(webpFrame(input));
97
97
  },
98
- file: () => webp.animationFile(chunks, width, height, toPlays(loopCount), alpha, exifData(resolved))
98
+ file: () => webp.animationFile(chunks, width, height, toPlays(loops), alpha, exifData(resolved))
99
99
  }, optimize);
100
100
  }
101
- static __gif__(width, height, { loopCount = -1, metadata = {}, optimize = true, quality: qualityOption = 95 }) {
102
- const quality = finite(qualityOption, 'quality');
103
- canvas(width, height, loopCount);
104
- fitLoops(loopCount, 'GIF');
101
+ static __gif__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85 }) {
102
+ const checked = paletteOptions(colors, dither, ditherStrength);
103
+ const palette = { colors: checked.colors, dither: checked.dither, strength: checked.strength };
104
+ const loops = fitLoops(loopCount(count), 'GIF');
105
+ canvas(width, height);
105
106
  const comments = gifComments(resolveMetadata(metadata));
106
107
  let first = null, restores = false;
107
108
  const rest = [];
108
109
  return new AnimationEncoder(width, height, {
109
- optimize: { replace: false, even: false, alpha: 'frame', palette: 256, cover: true },
110
+ name: 'GIF',
111
+ optimize: { replace: false, even: false, alpha: 'frame', palette: 256, cover: true, maxDuration: maxDuration('GIF') },
110
112
  async frame(f, optimized) {
111
113
  if (!first && optimized)
112
114
  coverCanvas(f, width, height);
@@ -117,24 +119,25 @@ export class AnimationEncoder {
117
119
  if (!first)
118
120
  first = gif;
119
121
  else
120
- rest.push(gifCodec.encodeFrame(gif, quality, gif.dispose === 3));
122
+ rest.push(gifCodec.encodeFrame(gif, palette, gif.dispose === 3));
121
123
  },
122
124
  file() {
123
125
  const f = first;
124
- return concat([gifCodec.header(width, height, loopCount, comments), gifCodec.encodeFrame(f, quality, f.dispose === 3 || restores), ...rest, new Uint8Array([0x3b])]);
126
+ return concat([gifCodec.header(width, height, loops, comments), gifCodec.encodeFrame(f, palette, f.dispose === 3 || restores), ...rest, new Uint8Array([0x3b])]);
125
127
  }
126
128
  }, optimize);
127
129
  }
128
- static __apng__(width, height, { loopCount = -1, metadata = {}, optimize = true, compression: compressionOption = 4 }) {
130
+ static __apng__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, compression: compressionOption = 4 }) {
129
131
  const compression = compressionLevel(compressionOption);
130
- canvas(width, height, loopCount);
131
- fitLoops(loopCount, 'APNG');
132
+ const loops = fitLoops(loopCount(count), 'APNG');
133
+ canvas(width, height);
132
134
  const text = pngText(resolveMetadata(metadata));
133
135
  const stored = [];
134
136
  const cost = new png.AlphaCost();
135
137
  let blended = false;
136
138
  return new AnimationEncoder(width, height, {
137
- optimize: { replace: true, even: false, alpha: () => cost.cost() },
139
+ name: 'APNG',
140
+ optimize: { replace: true, even: false, alpha: () => cost.cost(), maxDuration: maxDuration('APNG') },
138
141
  async frame(f, optimized) {
139
142
  let frame;
140
143
  if (optimized) {
@@ -169,16 +172,14 @@ export class AnimationEncoder {
169
172
  const format = scanner.format(), encoded = [];
170
173
  for await (const { pixels, ...f } of frames())
171
174
  encoded.push({ ...f, data: await png.frameData(pixels, f.width, f.height, format, compression) });
172
- return png.animationFile(encoded, width, height, toPlays(loopCount), format, text);
175
+ return png.animationFile(encoded, width, height, toPlays(loops), format, text);
173
176
  }
174
177
  }, optimize);
175
178
  }
176
179
  }
177
- function canvas(width, height, loopCount) {
180
+ function canvas(width, height) {
178
181
  if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1)
179
182
  throw new RangeError(`Invalid canvas size: ${width}x${height}`);
180
- if (loopCount !== Infinity && (!Number.isInteger(loopCount) || loopCount < -1))
181
- throw new RangeError('Invalid loop count');
182
183
  }
183
184
  function webpFrame(f) {
184
185
  let { x, y, width: w, height: h, pixels } = f;