imagescript 4.0.0-rc.1 → 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.
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
@@ -24,7 +24,7 @@ npm install imagescript # Node.js, Bun and bundlers
24
24
  deno add jsr:@matmen/imagescript # Deno
25
25
  ```
26
26
 
27
- Upgrading from 3.x? Read [Migrating to 4.0](https://imagescript.dev/documents/Migrating_to_4.0.html) first.
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
28
 
29
29
  Without a bundler, import it from jsDelivr in the browser:
30
30
 
@@ -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 |
@@ -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 } from "./util/options.js";
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;
@@ -33,12 +33,12 @@ export class AnimationEncoder {
33
33
  const image = own ? own.image : frame;
34
34
  if (!(image instanceof Image))
35
35
  throw new TypeError('encoder.add() takes a Frame or an Image');
36
- const duration = options.duration ?? own?.duration ?? 100;
37
- const x = options.xOffset ?? own?.xOffset ?? 0, y = options.yOffset ?? own?.yOffset ?? 0;
38
- if (finite(duration, 'frame duration') < 0)
36
+ const duration = finite(options.duration ?? own?.duration ?? 100, 'frame duration');
37
+ if (duration < 0)
39
38
  throw new RangeError('Invalid frame duration');
40
- finite(x, 'x offset');
41
- 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;
42
42
  const disposal = options.disposalMode !== undefined ? Frame.__convert_disposal_mode__(options.disposalMode) : own ? own.__disposal_id__ : 1;
43
43
  const input = {
44
44
  x, y, width: image.width, height: image.height, duration, disposal,
@@ -83,7 +83,8 @@ export class AnimationEncoder {
83
83
  chunks.push(await webp.frameChunk(f, lossy, effort));
84
84
  };
85
85
  return new AnimationEncoder(width, height, {
86
- 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') },
87
88
  async frame(f, optimized) {
88
89
  if (optimized)
89
90
  return add(f);
@@ -106,7 +107,8 @@ export class AnimationEncoder {
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);
@@ -134,7 +136,8 @@ export class AnimationEncoder {
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) {
package/dist/animation.js CHANGED
@@ -6,19 +6,19 @@ 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 } from "./image.js";
9
+ import { Image, resizeArguments, insideSize, alignedPixels } 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, color as checkColor } from "./util/options.js";
15
+ import { checkOptions, finite, compressionLevel, loopCount, toPlays, fromPlays, fitLoops, fitDuration, maxDuration, color as checkColor } from "./util/options.js";
16
16
  import { MAX_PIXELS, decoding } 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 }) => {
20
20
  const image = new Image(width, height);
21
- image.bitmap = pixels;
21
+ image.bitmap = alignedPixels(pixels);
22
22
  return new Frame(image, { duration, disposalMode: 'background' });
23
23
  });
24
24
  }
@@ -207,7 +207,7 @@ export class Animation {
207
207
  return [];
208
208
  return png.compositeAnimation({ width, height, frames: this.__apngFrames__() }).map(({ pixels, duration }) => {
209
209
  const image = new Image(width, height);
210
- image.bitmap = pixels;
210
+ image.bitmap = alignedPixels(pixels);
211
211
  return new Frame(image, { duration, disposalMode: 'background' });
212
212
  });
213
213
  }
@@ -239,19 +239,23 @@ export class Animation {
239
239
  return new Frame(clipped, { ...options, xOffset: left, yOffset: top });
240
240
  });
241
241
  }
242
- __validate__() {
243
- for (const frame of this.frames)
242
+ __validate__(format) {
243
+ if (!this.length)
244
+ throw new Error('An animation needs at least one frame');
245
+ for (const frame of this.frames) {
244
246
  if (!(frame instanceof Frame))
245
247
  throw new Error('Animation contains invalid frames');
248
+ fitDuration(frame.duration, format);
249
+ }
246
250
  }
247
251
  async encodeGIF(options = {}) {
248
252
  checkOptions(options, 'encodeGIF({ colors: 64 })');
249
253
  const { colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85, metadata = {}, optimize = true } = options;
250
254
  const palette = paletteOptions(colors, dither, ditherStrength);
251
255
  const loops = fitLoops(this.loopCount, 'GIF');
252
- this.__validate__();
256
+ this.__validate__('GIF');
253
257
  const frames = optimize
254
- ? this.__optimized__({ replace: false, even: false, alpha: 'frame', palette: 256, cover: true }).map(f => ({ ...f, dispose: f.dispose ? 3 : 1 }))
258
+ ? this.__optimized__({ replace: false, even: false, alpha: 'frame', palette: 256, cover: true, maxDuration: maxDuration('GIF') }).map(f => ({ ...f, dispose: f.dispose ? 3 : 1 }))
255
259
  : Array.from(this.__clipped_frames__(), frame => ({
256
260
  x: frame.xOffset,
257
261
  y: frame.yOffset,
@@ -268,11 +272,9 @@ export class Animation {
268
272
  checkOptions(options, 'encodeAPNG({ compression: 9 })');
269
273
  const { compression = 4, metadata = {}, optimize = true } = options;
270
274
  const loops = fitLoops(this.loopCount, 'APNG');
271
- this.__validate__();
272
- if (!this.length)
273
- throw new Error('An animation needs at least one frame');
275
+ this.__validate__('APNG');
274
276
  const frames = optimize
275
- ? this.__optimized__({ replace: true, even: false, alpha: frames => png.alphaCost(frames.map(f => f.pixels)) }).map(f => ({ ...f, dispose: f.dispose ? 1 : 0 }))
277
+ ? this.__optimized__({ replace: true, even: false, alpha: frames => png.alphaCost(frames.map(f => f.pixels)), maxDuration: maxDuration('APNG') }).map(f => ({ ...f, dispose: f.dispose ? 1 : 0 }))
276
278
  : this.__apngFrames__().map(({ blend: _, ...f }) => f);
277
279
  return png.encodeAnimation(frames, this.width, this.height, toPlays(loops), compressionLevel(compression), pngText(resolveMetadata(metadata)));
278
280
  }
@@ -280,12 +282,10 @@ export class Animation {
280
282
  checkOptions(options, 'animation.encodeWebP({ quality: 80 })');
281
283
  const { metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 } = options;
282
284
  const loops = fitLoops(this.loopCount, 'WebP');
283
- this.__validate__();
284
- if (!this.length)
285
- throw new Error('An animation needs at least one frame');
285
+ this.__validate__('WebP');
286
286
  const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
287
287
  const tolerance = lossy ? webp.lossyTolerance(lossy.quality) : undefined;
288
- const frames = optimize ? this.__optimized__({ replace: true, even: true, alpha: 'frame', tolerance }) : this.__webpFrames__();
288
+ const frames = optimize ? this.__optimized__({ replace: true, even: true, alpha: 'frame', tolerance, maxDuration: maxDuration('WebP') }) : this.__webpFrames__();
289
289
  return webp.encodeAnimation(frames, this.width, this.height, toPlays(loops), exifData(resolveMetadata(metadata)), lossy, effort);
290
290
  }
291
291
  __webpFrames__() {
@@ -399,7 +399,7 @@ export class Animation {
399
399
  let orientation = 1;
400
400
  for await (const decoded of jxl.frames(data, maxPixels, toneMapping, threads)) {
401
401
  const image = new Image(decoded.width, decoded.height);
402
- image.bitmap = decoded.pixels;
402
+ image.bitmap = alignedPixels(decoded.pixels);
403
403
  frames.push(new Frame(image, { duration: decoded.duration, disposalMode: 'background' }));
404
404
  orientation = decoded.orientation;
405
405
  loops = fromPlays(decoded.loopCount);
@@ -1487,7 +1487,7 @@ export class TileDecoder {
1487
1487
  const eobTok = m.symbol(cdf, eobCdf + ctx * 4, 2);
1488
1488
  let tok = eobTok + 1;
1489
1489
  let levelTok = tok * 0x41;
1490
- let mag = 0;
1490
+ let mag;
1491
1491
  let scanTable = null, stride, shift, shift2, mask, offsets = 0;
1492
1492
  if (txClass === TX_CLASS_2D) {
1493
1493
  const nonsquare = tx >= RTX_4X8 ? 1 : 0;
@@ -928,7 +928,7 @@ class TileEncoder {
928
928
  const w = tdim(tx, W) * 4, h = tdim(tx, H) * 4, sw = Math.min(w, 32), sh = Math.min(h, 32);
929
929
  const sx = plane ? this.ssx : 0, sy = plane ? this.ssy : 0;
930
930
  const vw = Math.max(0, Math.min(w, (f.width + sx >> sx) - px)), vh = Math.max(0, Math.min(h, (f.height + sy >> sy) - py));
931
- let eob = -1;
931
+ let eob;
932
932
  if (!(this.w && b.skip)) {
933
933
  const res = this.res, coefs = this.coefs, q = this.q;
934
934
  let sse = 0;
@@ -214,7 +214,7 @@ export function readICC(r) {
214
214
  const COMMON_TAGS = ['rTRC', 'rXYZ', 'cprt', 'wtpt', 'bkpt', 'rXYZ', 'gXYZ', 'bXYZ', 'kXYZ', 'rTRC', 'gTRC', 'bTRC', 'kTRC', 'chad', 'desc', 'chrm', 'dmnd', 'dmdd', 'lumi'];
215
215
  const COMMON_DATA = ['XYZ ', 'desc', 'text', 'mluc', 'para', 'curv', 'sf32', 'gbd '];
216
216
  export function decodeICC(stream) {
217
- let at = 0;
217
+ let at;
218
218
  const fail = () => {
219
219
  throw new RangeError('invalid ICC stream');
220
220
  };
@@ -280,7 +280,7 @@ export function findPatches(planes, stride, width, height, distance, numExtra) {
280
280
  maxH = Math.max(maxH, p.h);
281
281
  }
282
282
  let refW = Math.max(maxW, Math.sqrt(total)), refH = Math.max(maxH, Math.sqrt(total));
283
- let spots = [], usedH = 0;
283
+ let spots = [], usedH;
284
284
  for (;;) {
285
285
  refW = Math.floor(refW * 1.05 + 1);
286
286
  refH = Math.floor(refH * 1.05 + 1);
@@ -93,7 +93,7 @@ function inflate(dat, buf) {
93
93
  if (!sl)
94
94
  return buf.subarray(0, 0);
95
95
  const tbts = sl * 8;
96
- let final = 0, pos = 0, bt = 0;
96
+ let final, pos = 0, bt = 0;
97
97
  do {
98
98
  let lm, dm, lbt, dbt;
99
99
  final = bits(dat, pos, 1);
package/dist/colors.js CHANGED
@@ -135,6 +135,8 @@ export class Colors {
135
135
  else if (positions.length === 2) {
136
136
  const gradient = gradientBetween(values[0], values[1]);
137
137
  return position => {
138
+ if (Number.isNaN(position))
139
+ throw new RangeError(`Invalid gradient position: ${position}`);
138
140
  if (position <= positions[0])
139
141
  return values[0];
140
142
  if (position >= positions[1])
@@ -150,6 +152,8 @@ export class Colors {
150
152
  if (minPos === undefined)
151
153
  continue;
152
154
  const maxPos = positions[i];
155
+ if (maxPos === minPos)
156
+ continue;
153
157
  let minVal = values[i - 1];
154
158
  if (minVal === undefined)
155
159
  minVal = values[i];
@@ -157,6 +161,12 @@ export class Colors {
157
161
  const gradient = gradientBetween(minVal, maxVal);
158
162
  gradients.push({ min: minPos, max: maxPos, gradient });
159
163
  }
164
+ if (!gradients.length)
165
+ return position => {
166
+ if (Number.isNaN(position))
167
+ throw new RangeError(`Invalid gradient position: ${position}`);
168
+ return position <= minDef ? values[0] : values[values.length - 1];
169
+ };
160
170
  return position => {
161
171
  if (position <= minDef)
162
172
  return gradients[0].gradient(0);
package/dist/frame.d.ts CHANGED
@@ -55,14 +55,17 @@ export declare class Frame {
55
55
  * @param duration Milliseconds, a finite number from 0
56
56
  */
57
57
  set duration(duration: number);
58
- /** The frame's horizontal offset in the animation (a finite number, else it throws a RangeError) */
58
+ /**
59
+ * The frame's horizontal offset in the animation: an integer, values with a fraction are truncated like image sizes
60
+ * (a value that isn't a finite number throws a RangeError)
61
+ */
59
62
  get xOffset(): number;
60
63
  /**
61
64
  * Sets the horizontal offset
62
65
  * @param x The offset in pixels
63
66
  */
64
67
  set xOffset(x: number);
65
- /** The frame's vertical offset in the animation (a finite number, else it throws a RangeError) */
68
+ /** The frame's vertical offset in the animation: an integer, like {@link Frame.xOffset} */
66
69
  get yOffset(): number;
67
70
  /**
68
71
  * Sets the vertical offset
package/dist/frame.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Image } from "./image.js";
2
- import { checkOptions, finite } from "./util/options.js";
2
+ import { checkOptions, finite, oneOf } from "./util/options.js";
3
3
  const DISPOSAL_MODES = ['any', 'keep', 'previous', 'background'];
4
4
  export class Frame {
5
5
  __image__;
@@ -8,10 +8,7 @@ export class Frame {
8
8
  __y__ = 0;
9
9
  __disposalMode__ = 1;
10
10
  static __convert_disposal_mode__(mode) {
11
- const id = DISPOSAL_MODES.indexOf(mode);
12
- if (id < 0)
13
- throw new RangeError('Invalid disposal mode');
14
- return id;
11
+ return DISPOSAL_MODES.indexOf(oneOf(mode, DISPOSAL_MODES, 'disposal mode'));
15
12
  }
16
13
  constructor(image, options = {}) {
17
14
  if (!(image instanceof Image))
@@ -51,13 +48,13 @@ export class Frame {
51
48
  return this.__x__;
52
49
  }
53
50
  set xOffset(x) {
54
- this.__x__ = finite(x, 'x offset');
51
+ this.__x__ = Math.trunc(finite(x, 'x offset')) || 0;
55
52
  }
56
53
  get yOffset() {
57
54
  return this.__y__;
58
55
  }
59
56
  set yOffset(y) {
60
- this.__y__ = finite(y, 'y offset');
57
+ this.__y__ = Math.trunc(finite(y, 'y offset')) || 0;
61
58
  }
62
59
  get disposalMode() {
63
60
  return DISPOSAL_MODES[this.__disposalMode__];
package/dist/gainmap.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Image } from "./image.js";
1
+ import { Image, alignedPixels } from "./image.js";
2
2
  import * as jpeg from "./codecs/jpeg.js";
3
3
  import * as codec from "./codecs/gainmap.js";
4
4
  import { view } from "./util/mem.js";
@@ -70,7 +70,7 @@ export class GainMap {
70
70
  static __from_jpeg__(map, params, apple = 0) {
71
71
  const { width, height, pixels } = jpeg.decode(map);
72
72
  const image = new Image(width, height);
73
- image.bitmap = pixels;
73
+ image.bitmap = alignedPixels(pixels);
74
74
  if (apple) {
75
75
  const table = new Uint8Array(256);
76
76
  for (let v = 0; v < 256; v++)
package/dist/image.d.ts CHANGED
@@ -307,11 +307,26 @@ export interface RenderSVGOptions {
307
307
  */
308
308
  scale?: number;
309
309
  /**
310
- * Maximum total pixels in the rendered output. Output over the limit throws a RangeError. Raster images decoded
311
- * from embedded data are limited too and omitted if they exceed it; already-decoded {@link Image} values are used
312
- * as supplied. Default: `268402689` (16383²); `Infinity` disables the limit
310
+ * Maximum total pixels in the rendered output. Output over the limit throws a RangeError before anything is
311
+ * rendered. It's also the default of {@link RenderSVGOptions.maxLayerPixels} and
312
+ * {@link RenderSVGOptions.maxImagePixels}. Default: `268402689` (16383²); `Infinity` disables the limit
313
313
  */
314
314
  maxPixels?: number;
315
+ /**
316
+ * Maximum pixels of the layers rendering uses at once, the output's included. Groups with opacity, masks, clip
317
+ * paths of nested viewports, filters and blend modes are each rendered into a layer of their own (up to the
318
+ * output's size, 16 bytes per pixel) while their content is drawn, so deeply nested ones multiply the memory a
319
+ * small SVG takes. Exceeding it throws a RangeError. With the defaults, rendering can take about 90 bytes per pixel
320
+ * of `maxPixels` (64 for the layers, up to 20 for the images, 4 for the output): lower `maxPixels` to bound it for
321
+ * untrusted SVGs. Default: `4 * maxPixels`; `Infinity` disables the limit
322
+ */
323
+ maxLayerPixels?: number;
324
+ /**
325
+ * Maximum total pixels of the raster images the SVG references (data URIs and {@link RenderSVGOptions.images}),
326
+ * decoded together; already-decoded {@link Image} values are used as supplied and don't count. Drawing an image
327
+ * beyond the limit throws a RangeError. Default: `maxPixels`; `Infinity` disables the limit
328
+ */
329
+ maxImagePixels?: number;
315
330
  /**
316
331
  * Fonts for `<text>` (TrueType, OpenType or WOFF; not WOFF2 or some newer OpenType outline formats such as CFF2):
317
332
  * each text gets the face its `font-family`, `font-weight`, `font-style`
@@ -327,8 +342,9 @@ export interface RenderSVGOptions {
327
342
  * Images for the `<image>` elements (and `feImage`) by their `href`, the same string the SVG uses: with
328
343
  * `images: { 'logo.png': bytes }`, `<image href="logo.png" .../>` draws the image. Values are encoded images (PNG,
329
344
  * JPEG, WebP, GIF's first frame, ...) or {@link Image}s, decoded like data URI images are, and only for the hrefs
330
- * the SVG references. Nothing else is read: no files and no URLs, so an href that isn't given (and isn't a data URI)
331
- * draws nothing. SVG documents can't be given this way, use a data URI for them. Default: `{}`
345
+ * the SVG references. Nothing else is read: no files and no URLs, so drawing an image whose href isn't given (and
346
+ * isn't a data URI) throws, as does drawing one that can't be decoded. SVG documents can't be given this way, use a
347
+ * data URI for them. Default: `{}`
332
348
  */
333
349
  images?: Record<string, BinaryData | Image>;
334
350
  }
@@ -350,6 +366,11 @@ export interface RenderTextOptions extends TextStyleOptions, TextLayoutOptions {
350
366
  size: number;
351
367
  /** The text color. Default: `0xffffffff` */
352
368
  color?: Color;
369
+ /**
370
+ * Maximum total pixels of the rendered image (the outline included): larger text throws a RangeError before its
371
+ * pixels are allocated. Default: `268402689` (16383²); `Infinity` disables the limit
372
+ */
373
+ maxPixels?: number;
353
374
  }
354
375
  /** Options of {@link Image.decode}, {@link Animation.decode} and {@link decode} */
355
376
  export interface DecodeOptions {
@@ -369,7 +390,10 @@ export interface DecodeOptions {
369
390
  /**
370
391
  * The maximum total pixels to decode. An image declaring more pixels throws a RangeError before its pixel buffer
371
392
  * is allocated, helping prevent a small or untrusted file from requesting an enormous amount of memory.
372
- * {@link Animation.decode} counts all frames together because each frame uses a full canvas. Default:
393
+ * {@link Animation.decode} counts all frames together because each frame uses a full canvas. The decoded image
394
+ * takes 4 bytes per pixel (about 1 GiB at the default), and decoding needs more while it runs: for 8-bit images,
395
+ * about 4-7 bytes per pixel for PNG, JPEG, WebP, GIF and the simpler formats, about 14 for AVIF and about 30 for
396
+ * JPEG XL (more with high bit depths). Lower it to bound the memory of servers decoding untrusted files. Default:
373
397
  * `268402689` (16383²); `Infinity` disables the limit
374
398
  */
375
399
  maxPixels?: number;
@@ -546,14 +570,14 @@ export declare class Image {
546
570
  set gainMap(gainMap: GainMap | null);
547
571
  /**
548
572
  * The image's RGBA pixel data (red, green, blue and transparency, four bytes per pixel). It can be replaced by any
549
- * 8-bit array with width * height * 4 bytes
550
- * (it is used as is, without copying). Direct changes to this array or {@link Image.setPixelAt} don't update the
551
- * image's gain map.
573
+ * 8-bit array with width * height * 4 bytes starting at a byte offset divisible by 4 (it is used as is, without
574
+ * copying). Direct changes to this array or {@link Image.setPixelAt} don't update the image's gain map.
552
575
  */
553
576
  get bitmap(): Uint8ClampedArray;
554
577
  /**
555
578
  * Replaces the pixel data
556
- * @param bitmap The new RGBA data, width * height * 4 bytes (used as is, without copying)
579
+ * @param bitmap The new RGBA data, width * height * 4 bytes (used as is, without copying, so its byte offset has to be
580
+ * divisible by 4: the image reads it as 32-bit pixels too)
557
581
  */
558
582
  set bitmap(bitmap: Uint8ClampedArray | Uint8Array);
559
583
  /** A short description for debugging, e.g. `Image<64x64>` */
@@ -608,7 +632,8 @@ export declare class Image {
608
632
  setPixelAt(x: number, y: number, color: Color): this;
609
633
  /**
610
634
  * Fills the image data with the supplied color
611
- * @param color The color, or a function returning the color of each pixel
635
+ * @param color The color, or a function returning the color of each pixel (checked like any color: a result that
636
+ * isn't one throws a RangeError)
612
637
  */
613
638
  fill(color: Color | ColorFunction): this;
614
639
  /**
@@ -943,7 +968,8 @@ export declare class Image {
943
968
  * Supports shapes, paths, transforms, use/symbol, CSS styles, gradients, patterns, strokes, markers, clip paths,
944
969
  * masks, opacity, blend modes, filters (all primitives and the filter functions) and images embedded as data URIs
945
970
  * (PNG, JPEG, GIF, WebP, SVG) or given with {@link RenderSVGOptions.images}, and text with the given or embedded fonts
946
- * (see {@link RenderSVGOptions.fonts}). Hrefs are resolved from the options and the data URIs only, never from files or URLs.
971
+ * (see {@link RenderSVGOptions.fonts}). Hrefs are resolved from the options and the data URIs only, never from files or URLs:
972
+ * drawing an image that isn't given, or can't be decoded, throws.
947
973
  * @example
948
974
  * ```ts
949
975
  * const logo = await Image.renderSVG(