imagescript 4.0.0-rc.4 → 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 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: 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
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
@@ -45,7 +45,7 @@ calling thread: the output is the same, only slower, and nothing warns about it.
45
45
  origin, so the jsDelivr example above runs single-threaded; serve the package from your own origin (on a cross-origin
46
46
  isolated page) to get threads.
47
47
 
48
- Bundlers that write one file (esbuild, webpack) don't copy the worker's module: serve `dist/util/worker.js` next to the
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
49
  bundle, or the same single-threaded fallback is used. Vite and Rollup emit it.
50
50
 
51
51
  ---
@@ -90,6 +90,9 @@ and encoded as GIF, APNG or WebP, all at once or
90
90
  [frame by frame](https://imagescript.dev/classes/Animation.html#webpencoder). Lossless encoding keeps every pixel
91
91
  exactly; lossy encoding makes smaller files by approximating some image detail.
92
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
+
93
96
  Embedded color profiles are converted to sRGB, the standard color format for most screens, where supported. CMYK and
94
97
  lookup-table profiles are left unchanged.
95
98
 
@@ -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;
@@ -82,6 +84,7 @@ 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
89
  canvas(width, height, 'WebP');
87
90
  if (width > 1 << 24 || height > 1 << 24)
@@ -114,6 +117,7 @@ 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
122
  canvas(width, height, 'GIF');
119
123
  const comments = gifComments(resolveMetadata(metadata));
@@ -142,6 +146,7 @@ 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
151
  canvas(width, height, 'APNG');
147
152
  const text = pngText(resolveMetadata(metadata));
@@ -191,6 +196,8 @@ export class AnimationEncoder {
191
196
  }
192
197
  }
193
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}`);
196
203
  if (format === 'GIF' && (width > 0xffff || height > 0xffff))
@@ -192,7 +192,8 @@ export declare class Animation {
192
192
  * before and merges identical frames (unless the `optimize` option is false), so the file decodes to what the
193
193
  * animation shows, but not necessarily to the same frames. Semi-transparent pixels become opaque or transparent
194
194
  * after the frames are composited
195
- * @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)
196
197
  * @throws `Error` if the animation has no frames
197
198
  * @throws `RangeError` if the loop count or a frame's duration is more than GIF stores, or the canvas is wider or
198
199
  * higher than 65535 pixels
@@ -203,7 +204,8 @@ export declare class Animation {
203
204
  * the first frame. Each frame is stored as the area that changed since the frame before, identical frames are
204
205
  * merged (unless the `optimize` option is false): the file shows exactly the same animation, but doesn't
205
206
  * necessarily decode to the same frames
206
- * @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)
207
209
  * @throws `Error` if the animation has no frames
208
210
  * @throws `RangeError` if the loop count or a frame's duration is more than APNG stores
209
211
  */
@@ -212,7 +214,8 @@ export declare class Animation {
212
214
  * Encodes the animation as animated WebP, lossless or (with a quality) lossy. Each frame is stored as the area that
213
215
  * changed since the frame before, identical frames are merged (unless the `optimize` option is false): the file
214
216
  * shows the same animation, but doesn't necessarily decode to the same frames
215
- * @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)
216
219
  * @throws `Error` if the animation has no frames
217
220
  * @throws `RangeError` if the loop count or a frame's duration is more than WebP stores
218
221
  */
@@ -257,10 +260,13 @@ export declare class Animation {
257
260
  * const animation = await Animation.decode(gifBytes);
258
261
  * const webp = await animation.resize({ width: 320 }).encodeWebP({ quality: 75 });
259
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
260
266
  * @param input The binary data to decode
261
267
  * @param options See {@link DecodeOptions}
262
268
  * @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
269
+ * @throws `Error` if the data isn't a supported image, or is damaged or cut off before its first whole frame
264
270
  */
265
271
  static decode(input: BinaryData, options?: DecodeOptions): Promise<Animation>;
266
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";
15
+ import { checkOptions, oneOf, pixelLimit, checkThreads, finite, compressionLevel, loopCount, toPlays, fromPlays, fitLoops, fitDuration, maxDuration, boolean, color as checkColor } from "./util/options.js";
16
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))
@@ -305,6 +308,7 @@ export class Animation {
305
308
  async encodeGIF(options = {}) {
306
309
  checkOptions(options, 'encodeGIF({ colors: 64 })');
307
310
  const { colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85, metadata = {}, optimize = true } = options;
311
+ boolean(optimize, 'optimize');
308
312
  const palette = paletteOptions(colors, dither, ditherStrength);
309
313
  const loops = fitLoops(this.loopCount, 'GIF');
310
314
  this.__validate__('GIF');
@@ -325,6 +329,7 @@ export class Animation {
325
329
  async encodeAPNG(options = {}) {
326
330
  checkOptions(options, 'encodeAPNG({ compression: 9 })');
327
331
  const { compression = 4, metadata = {}, optimize = true } = options;
332
+ boolean(optimize, 'optimize');
328
333
  const loops = fitLoops(this.loopCount, 'APNG');
329
334
  this.__validate__('APNG');
330
335
  const frames = optimize
@@ -335,6 +340,7 @@ export class Animation {
335
340
  async encodeWebP(options = {}) {
336
341
  checkOptions(options, 'animation.encodeWebP({ quality: 80 })');
337
342
  const { metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 } = options;
343
+ boolean(optimize, 'optimize');
338
344
  const loops = fitLoops(this.loopCount, 'WebP');
339
345
  this.__validate__('WebP');
340
346
  const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
@@ -408,6 +414,9 @@ export class Animation {
408
414
  }
409
415
  static async __decode__(input, options) {
410
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');
411
420
  const orient = (frames, orientation) => {
412
421
  if (applyOrientation && orientation > 1)
413
422
  for (const frame of frames)
@@ -431,11 +440,14 @@ export class Animation {
431
440
  const frames = orient(profile(canvasFrames(decoded.width, decoded.height, webp.composite(decoded)), decoded.icc), decoded.orientation);
432
441
  const animation = new Animation(frames, { loopCount: fromPlays(decoded.loopCount), width: frames[0]?.width ?? decoded.width, height: frames[0]?.height ?? decoded.height });
433
442
  animation.__animationSignal__ = animated;
443
+ if (!animated)
444
+ for (const frame of frames)
445
+ frame.duration = 100;
434
446
  return animation;
435
447
  }
436
448
  if (type === 'png' && !png.isAnimated(data)) {
437
449
  const image = await Image.decode(data, { maxPixels, applyOrientation, applyColorProfile });
438
- return new Animation(canvasFrames(image.width, image.height, [{ pixels: image.bitmap, duration: 0 }]), { loopCount: Infinity, width: image.width, height: image.height });
450
+ return new Animation(canvasFrames(image.width, image.height, [{ pixels: image.bitmap, duration: 100 }]), { loopCount: Infinity, width: image.width, height: image.height });
439
451
  }
440
452
  if (type === 'png') {
441
453
  const decoded = await png.decodeAnimation(data, false, maxPixels);
@@ -482,11 +494,14 @@ export class Animation {
482
494
  }
483
495
  const animation = new Animation(frames, { loopCount: animated ? loops : Infinity, ...(frames.length ? { width: frames[0].width, height: frames[0].height } : {}) });
484
496
  animation.__animationSignal__ = animated;
497
+ if (!animated)
498
+ for (const frame of frames)
499
+ frame.duration = 100;
485
500
  return animation;
486
501
  }
487
502
  if (type) {
488
503
  const image = await Image.decode(data, { maxPixels, applyOrientation, applyColorProfile, toneMapping, gainMap, threads });
489
- return new Animation([new Frame(image, { duration: 0 })], { width: image.width, height: image.height });
504
+ return new Animation([new Frame(image)], { width: image.width, height: image.height });
490
505
  }
491
506
  throw new Error('Unsupported image type');
492
507
  }
@@ -499,7 +514,10 @@ export class Animation {
499
514
  }
500
515
  }
501
516
  function canvasSize(width, height) {
517
+ finite(width, 'width');
518
+ finite(height, 'height');
502
519
  if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1)
503
520
  throw new RangeError(`Invalid canvas size: ${width}x${height}`);
504
521
  return [width, height];
505
522
  }
523
+ describe(Animation, animation => ({ width: animation.width, height: animation.height, duration: animation.duration, frames: animation.frames.length }));
@@ -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)
@@ -25,6 +25,7 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
25
25
  let orientation = 1;
26
26
  const profile = [];
27
27
  let restartInterval = 0;
28
+ let scans = 0;
28
29
  let pos = 2;
29
30
  const u16 = (offset) => data[offset] << 8 | data[offset + 1];
30
31
  while (pos < data.length) {
@@ -150,6 +151,7 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
150
151
  const spectralEnd = data[p + 1];
151
152
  const successiveHigh = data[p + 2] >> 4;
152
153
  const successiveLow = data[p + 2] & 15;
154
+ scans++;
153
155
  pos = decodeScan(data, end, frame, components, restartInterval, spectralStart, spectralEnd, successiveHigh, successiveLow);
154
156
  continue;
155
157
  }
@@ -158,6 +160,8 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
158
160
  }
159
161
  if (!frame)
160
162
  throw new Error('JPEG: missing frame header');
163
+ if (!scans)
164
+ throw new Error('JPEG: no image data (the file is truncated)');
161
165
  const icc = profile.length && Array.from(profile).every(Boolean) ? concat(profile) : undefined;
162
166
  return { width: frame.width, height: frame.height, pixels: output(frame, adobe, jfif, transform), orientation, icc };
163
167
  }
@@ -222,9 +226,10 @@ function buildHuffmanTable(counts, symbols) {
222
226
  function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah, al) {
223
227
  let pos = offset;
224
228
  let buffer = 0, bits = 0;
229
+ let padding = 0;
225
230
  const fill = () => {
226
231
  while (bits <= 24) {
227
- let byte = 0;
232
+ let byte = 0, fed = false;
228
233
  if (pos < data.length) {
229
234
  byte = data[pos];
230
235
  if (byte === 0xff) {
@@ -232,11 +237,17 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
232
237
  if (next === 0x00)
233
238
  pos += 2;
234
239
  else
235
- byte = 0;
240
+ fed = true;
236
241
  }
237
242
  else
238
243
  pos++;
239
244
  }
245
+ else
246
+ fed = true;
247
+ if (fed) {
248
+ byte = 0;
249
+ padding++;
250
+ }
240
251
  buffer = buffer << 8 | byte;
241
252
  bits += 8;
242
253
  }
@@ -252,6 +263,7 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
252
263
  fill();
253
264
  return buffer >>> --bits & 1;
254
265
  };
266
+ let broken = false;
255
267
  const huffman = (table) => {
256
268
  if (!table)
257
269
  throw new Error('JPEG: missing huffman table');
@@ -265,8 +277,12 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
265
277
  let length = 10;
266
278
  let code = buffer >>> bits - 10 & 1023;
267
279
  while (code > table.maxCode[length]) {
268
- if (++length > 16)
269
- throw new Error('JPEG: invalid huffman code');
280
+ if (++length > 16) {
281
+ if (!restartInterval)
282
+ throw new Error('JPEG: invalid huffman code');
283
+ broken = true;
284
+ return 0;
285
+ }
270
286
  code = buffer >>> bits - length & (1 << length) - 1;
271
287
  }
272
288
  bits -= length;
@@ -274,6 +290,10 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
274
290
  };
275
291
  const extend = (value, size) => value < 1 << size - 1 ? value + (-1 << size) + 1 : value;
276
292
  const receiveExtend = (size) => size ? extend(getBits(size), size) : 0;
293
+ const checkComplete = () => {
294
+ if (padding * 8 > bits)
295
+ throw new Error('JPEG: the scan data is truncated');
296
+ };
277
297
  let eobrun = 0;
278
298
  const decodeBaseline = (component, offset) => {
279
299
  const coefficients = component.coefficients;
@@ -397,11 +417,12 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
397
417
  const column = unit % component.blocksPerLine;
398
418
  if (sequential) {
399
419
  pending = row;
400
- decodeBlock(component, column * 64);
420
+ if (!broken)
421
+ decodeBlock(component, column * 64);
401
422
  if (column === component.blocksPerLine - 1)
402
423
  finish();
403
424
  }
404
- else
425
+ else if (!broken)
405
426
  decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64);
406
427
  }
407
428
  else {
@@ -414,7 +435,8 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
414
435
  for (let h = 0; h < component.h; h++) {
415
436
  const row = sequential ? v : mcuRow * component.v + v;
416
437
  const column = mcuColumn * component.h + h;
417
- decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64);
438
+ if (!broken)
439
+ decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64);
418
440
  }
419
441
  if (sequential && mcuColumn === frame.mcusPerLine - 1)
420
442
  finish();
@@ -422,16 +444,23 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
422
444
  }
423
445
  if (unit >= total)
424
446
  break;
447
+ const short = !broken && padding * 8 > bits;
448
+ broken = false;
425
449
  bits = 0;
426
450
  buffer = 0;
451
+ padding = 0;
427
452
  while (pos + 1 < data.length && !(data[pos] === 0xff && data[pos + 1] >= 0xd0 && data[pos + 1] <= 0xd7)) {
428
453
  if (data[pos] === 0xff && data[pos + 1] !== 0x00 && data[pos + 1] !== 0xff) {
454
+ if (short)
455
+ throw new Error('JPEG: the scan data is truncated');
429
456
  finish();
430
457
  return pos;
431
458
  }
432
459
  pos++;
433
460
  }
434
461
  if (pos + 1 >= data.length) {
462
+ if (short)
463
+ throw new Error('JPEG: the scan data is truncated');
435
464
  finish();
436
465
  return pos;
437
466
  }
@@ -440,6 +469,8 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
440
469
  for (const component of components)
441
470
  component.pred = 0;
442
471
  }
472
+ if (!broken)
473
+ checkComplete();
443
474
  finish();
444
475
  return pos;
445
476
  }
@@ -227,7 +227,8 @@ export async function encodeVarDCT(rgba, width, height, options) {
227
227
  if (width < 1 || height < 1)
228
228
  throw new RangeError('JPEG XL: dimensions must be at least 1');
229
229
  const n = Math.min(options.threads, Math.ceil(height / 64), Math.max(4, Math.floor(width * height / PIXELS_PER_THREAD[options.effort])));
230
- const pool = { threads: n > 1 && width * height >= MIN_THREADED_PIXELS[options.effort] ? startThreads(n) : null };
230
+ const minimum = n < 4 ? Math.max(MIN_THREADED_PIXELS[options.effort], MIN_THREADED_PIXELS[0]) : MIN_THREADED_PIXELS[options.effort];
231
+ const pool = { threads: n > 1 && width * height >= minimum ? startThreads(n) : null };
231
232
  try {
232
233
  return await encode(rgba, width, height, options, pool);
233
234
  }
@@ -368,8 +368,12 @@ function parse(array) {
368
368
  break;
369
369
  }
370
370
  const chunk = array.subarray(start, end);
371
- if (end + 4 <= array.length && crc32(array.subarray(offset + 4, end)) !== view.getUint32(end))
372
- throw new Error('PNG: chunk checksum mismatch');
371
+ if (end + 4 <= array.length && crc32(array.subarray(offset + 4, end)) !== view.getUint32(end)) {
372
+ if (!(type & 0x20000000) || type === acTL || type === fcTL || type === fdAT)
373
+ throw new Error('PNG: chunk checksum mismatch');
374
+ offset = end + 4;
375
+ continue;
376
+ }
373
377
  if (type === IHDR) {
374
378
  if (length < 13)
375
379
  throw new Error('PNG: invalid IHDR');
@@ -136,7 +136,7 @@ export async function decode(data, maxPixels = MAX_PIXELS) {
136
136
  if (![0, 1, 2, 3, 5, 6].includes(photometric))
137
137
  throw new Error(`TIFF: photometric interpretation ${photometric} is not supported`);
138
138
  if (sampleFormat === 3 ? bps !== 32 && bps !== 64 : bps < 1 || bps > 32)
139
- throw new Error(`TIFF: ${bps}-bit samples are not supported`);
139
+ throw new Error(`TIFF: ${bps}-bit ${sampleFormat === 3 ? 'floating-point ' : ''}samples are not supported`);
140
140
  const colorChannels = { 0: 1, 1: 1, 2: 3, 3: 1, 5: 4, 6: 3 }[photometric];
141
141
  if (samplesPerPixel < colorChannels)
142
142
  throw new Error('TIFF: not enough samples per pixel');
@@ -294,7 +294,7 @@ export function decode(data, maxPixels = MAX_PIXELS) {
294
294
  inverseDCT(coeffs, b * 16, plane, cBase + (i >> 1) * 4 * cs + (i & 1) * 4, cs, ac >> b & 1);
295
295
  }
296
296
  }
297
- if (tokens.exhausted && d.exhausted)
297
+ if (tokens.exhausted || d.exhausted)
298
298
  throw new Error('VP8: unexpected end of data');
299
299
  }
300
300
  if (h.filterLevel)
@@ -8,7 +8,7 @@ import { encodeVP8, encodeAlpha } from "./vp8-enc.js";
8
8
  import { rgbaToYUV } from "./vp8-enc-dsp.js";
9
9
  import { orientation as exifOrientation } from "./exif.js";
10
10
  import { MAX_PIXELS, checkPixels } from "../util/limits.js";
11
- import { effort as checkEffort, quality as checkQuality } from "../util/options.js";
11
+ import { effort as checkEffort, quality as checkQuality, boolean as checkBoolean } from "../util/options.js";
12
12
  import { startThreads } from "../util/threads.js";
13
13
  const fourCC = (s) => s.charCodeAt(0) | s.charCodeAt(1) << 8 | s.charCodeAt(2) << 16 | s.charCodeAt(3) << 24;
14
14
  const RIFF = fourCC('RIFF'), WEBP = fourCC('WEBP');
@@ -40,6 +40,8 @@ const u24 = (d, o) => d[o] | d[o + 1] << 8 | d[o + 2] << 16;
40
40
  function decodeBitstream(list, maxPixels) {
41
41
  let alpha = null;
42
42
  for (const chunk of list) {
43
+ if ((chunk.type === ALPH || chunk.type === VP8L || chunk.type === VP8) && chunk.cut)
44
+ throw new Error('WebP: the image data is truncated');
43
45
  if (chunk.type === ALPH)
44
46
  alpha ??= chunk;
45
47
  else if (chunk.type === VP8L) {
@@ -295,10 +297,11 @@ export async function encode(rgba, width, height, exif, threads = 1, effort = 2)
295
297
  }
296
298
  export function lossyOptions(quality, effort, sharp, alphaQuality) {
297
299
  checkEffort(effort, 6);
300
+ const a = checkQuality(alphaQuality, 'alphaQuality');
301
+ checkBoolean(sharp, 'sharpYuv');
298
302
  if (quality === undefined)
299
303
  return undefined;
300
- const q = checkQuality(quality), a = checkQuality(alphaQuality, 'alphaQuality');
301
- return { quality: q, method: effort, sharp, alphaQuality: Math.round(a) };
304
+ return { quality: checkQuality(quality), method: effort, sharp, alphaQuality: Math.round(a) };
302
305
  }
303
306
  export async function encodeLossy(rgba, width, height, lossy, exif) {
304
307
  const { alpha, chunks } = await lossyChunks(rgba, width, height, lossy);
package/dist/colors.d.ts CHANGED
@@ -74,6 +74,9 @@ export declare class Colors {
74
74
  * Creates a multi-point gradient generator
75
75
  * @param stops The colors along the gradient: their positions (0..1) and colors (`{ 0: 0xff0000ff, 1: 0x00ff00ff }`),
76
76
  * or just the colors, evenly spaced (`[0xff0000ff, 0x00ff00ff]`), like {@link GradientOptions.stops}
77
+ * @remarks A stop may lie outside 0..1 (`{ 0: red, 2: blue }`): it is where it says, so the part between 0 and 1
78
+ * shows only part of the way between its colors. Before the first stop and after the last one, the gradient has
79
+ * their colors
77
80
  * @return The gradient generator. The function argument is the position in the gradient (0..1).
78
81
  */
79
82
  static gradient(stops: Record<number, Color> | Color[]): (position: number) => Color;
package/dist/colors.js CHANGED
@@ -73,7 +73,9 @@ function gradientBetween(startColor, endColor) {
73
73
  };
74
74
  }
75
75
  export class Colors {
76
- constructor() { }
76
+ constructor() {
77
+ throw new TypeError('Colors only has static methods, like Colors.fromRGBA()');
78
+ }
77
79
  static fromRGBA(r, g, b, a) {
78
80
  r = finite(r, 'red');
79
81
  g = finite(g, 'green');
@@ -122,6 +124,8 @@ export class Colors {
122
124
  return [h * 360, s, l, alpha];
123
125
  }
124
126
  static gradient(stops) {
127
+ if (typeof stops !== 'object' || stops === null)
128
+ throw new TypeError(`gradient() takes an array of colors or an object of positions and colors, not ${stops === null ? 'null' : typeof stops}`);
125
129
  let colors;
126
130
  if (Array.isArray(stops)) {
127
131
  if (!stops.length)
package/dist/frame.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Image } from "./image.js";
2
2
  import { checkOptions, finite, oneOf } from "./util/options.js";
3
+ import { describe } from "./util/inspect.js";
3
4
  const DISPOSAL_MODES = ['any', 'keep', 'previous', 'background'];
4
5
  export class Frame {
5
6
  __image__;
@@ -112,3 +113,4 @@ export class Frame {
112
113
  return this.__tracked__(image => image.outline(options));
113
114
  }
114
115
  }
116
+ describe(Frame, frame => ({ width: frame.width, height: frame.height, duration: frame.duration }));
package/dist/gainmap.d.ts CHANGED
@@ -107,14 +107,14 @@ export declare class GainMap {
107
107
  get hdrCapacityMin(): number;
108
108
  /**
109
109
  * Replaces the value (checked: an invalid one throws and the old one stays)
110
- * @param value A finite number from 0
110
+ * @param value A finite number from 0, below `hdrCapacityMax`
111
111
  */
112
112
  set hdrCapacityMin(value: number);
113
113
  /** log2 of the display headroom at which it applies fully (above `hdrCapacityMin`) */
114
114
  get hdrCapacityMax(): number;
115
115
  /**
116
116
  * Replaces the value (checked: an invalid one throws and the old one stays)
117
- * @param value A finite number
117
+ * @param value A finite number above `hdrCapacityMin`
118
118
  */
119
119
  set hdrCapacityMax(value: number);
120
120
  /** Whether the boost applies in the SDR image's color space (else in the HDR image's) */
package/dist/gainmap.js CHANGED
@@ -9,10 +9,8 @@ const perChannel = (value, name) => {
9
9
  if (typeof given !== 'number' && !Array.isArray(given))
10
10
  throw new TypeError(`${name} must be a number or an array of 3 numbers, not ${given === null ? 'null' : typeof given}`);
11
11
  const values = typeof value === 'number' ? [value, value, value] : Array.from(value);
12
- if (values.length === 1)
13
- values.push(values[0], values[0]);
14
12
  if (values.length !== 3)
15
- throw new RangeError(`${name} must be a number or an array of 3 numbers`);
13
+ throw new RangeError(`${name} must be a number or an array of 3 numbers, not ${values.length}`);
16
14
  return values.map(v => finite(v, name));
17
15
  };
18
16
  export class GainMap {
@@ -44,10 +42,17 @@ export class GainMap {
44
42
  const capacity = finite(value, 'hdrCapacityMin');
45
43
  if (capacity < 0)
46
44
  throw new RangeError('The gain map\'s hdrCapacityMin can\'t be negative');
45
+ if (this.__capacityMax__ !== undefined && !(capacity < this.__capacityMax__))
46
+ throw new RangeError(`The gain map's hdrCapacityMin must be below its hdrCapacityMax (${capacity} >= ${this.__capacityMax__})`);
47
47
  this.__capacityMin__ = capacity;
48
48
  }
49
49
  get hdrCapacityMax() { return this.__capacityMax__; }
50
- set hdrCapacityMax(value) { this.__capacityMax__ = finite(value, 'hdrCapacityMax'); }
50
+ set hdrCapacityMax(value) {
51
+ const capacity = finite(value, 'hdrCapacityMax');
52
+ if (this.__capacityMin__ !== undefined && !(capacity > this.__capacityMin__))
53
+ throw new RangeError(`The gain map's hdrCapacityMax (by default the largest max) must be above its hdrCapacityMin (${capacity} <= ${this.__capacityMin__})`);
54
+ this.__capacityMax__ = capacity;
55
+ }
51
56
  get useBaseColorSpace() { return this.__useBaseColorSpace__; }
52
57
  set useBaseColorSpace(value) {
53
58
  if (typeof value !== 'boolean')
@@ -123,8 +128,6 @@ export class GainMap {
123
128
  for (let c = 0; c < 3; c++)
124
129
  if (this.__max__[c] < this.__min__[c])
125
130
  throw new RangeError(`The gain map's max must be at least its min (${this.__max__[c]} < ${this.__min__[c]}; the values are checked together when the map is cloned or encoded)`);
126
- if (this.__capacityMax__ <= this.__capacityMin__)
127
- throw new RangeError(`The gain map's hdrCapacityMax (by default the largest max) must be above its hdrCapacityMin (${this.__capacityMax__} <= ${this.__capacityMin__})`);
128
131
  }
129
132
  get image() {
130
133
  return this.__pixels__;
@@ -206,9 +209,12 @@ export class GainMap {
206
209
  }
207
210
  async encodeJPEG(options) {
208
211
  checkOptions(options, 'gainMap.encodeJPEG({ quality: 80 })');
209
- let quality = options?.quality;
210
- if (quality !== undefined)
211
- quality = Math.max(1, checkQuality(quality));
212
+ const quality = options?.quality;
213
+ if (quality !== undefined) {
214
+ checkQuality(quality);
215
+ if (quality < 1)
216
+ throw new RangeError(`quality has to be between 1 and 100, not ${quality}`);
217
+ }
212
218
  return codec.mapWithMetadata(this.__body__(quality), this.__params__());
213
219
  }
214
220
  static async decode(data, options = {}) {
package/dist/image.d.ts CHANGED
@@ -242,7 +242,8 @@ export interface OutlineOptions {
242
242
  export interface GradientOptions {
243
243
  /**
244
244
  * The colors along the gradient: their positions (0..1) and colors (`{ 0: 0xff0000ff, 0.5: 0xffff00ff, 1: 0x00ff00ff }`),
245
- * or just the colors, evenly spaced (`[0xff0000ff, 0x00ff00ff]`), like {@link Colors.gradient} takes them
245
+ * or just the colors, evenly spaced (`[0xff0000ff, 0x00ff00ff]`), like {@link Colors.gradient} takes them. A
246
+ * position outside 0..1 is allowed, see {@link Colors.gradient}
246
247
  */
247
248
  stops: Record<number, Color> | Color[];
248
249
  }
@@ -349,7 +350,8 @@ export interface WebPEncodeOptions extends EncodeOptions {
349
350
  quality?: number;
350
351
  /**
351
352
  * Compression effort (0-6): higher values usually take longer but may make smaller files. For lossless images,
352
- * `0` prioritizes speed; `2` and above spend more time reducing file size
353
+ * `0` prioritizes speed; `2` and above spend more time reducing file size (lossless images are encoded the same at
354
+ * `2` and above)
353
355
  * @defaultValue `2`
354
356
  */
355
357
  effort?: number;
@@ -524,8 +526,9 @@ export interface DecodeOptions {
524
526
  * is allocated, helping prevent a small or untrusted file from requesting an enormous amount of memory.
525
527
  * {@link Animation.decode} counts all frames together because each frame uses a full canvas. The decoded image
526
528
  * takes 4 bytes per pixel (about 1 GiB at the default), and decoding needs more while it runs: for 8-bit images,
527
- * about 4-7 bytes per pixel for PNG, JPEG, WebP, GIF and the simpler formats, about 14 for AVIF and about 30 for
528
- * JPEG XL (more with high bit depths). Lower it to bound the memory of servers decoding untrusted files
529
+ * about 4-7 bytes per pixel for PNG, JPEG, WebP, GIF and the simpler formats, about 14 for AVIF and about 60 for
530
+ * lossy JPEG XL on one thread, about 110 with worker threads (more with high bit depths). Lower it to bound the
531
+ * memory of servers decoding untrusted files
529
532
  * @defaultValue `268402689` (16383²); `Infinity` disables the limit
530
533
  */
531
534
  maxPixels?: number;
@@ -562,7 +565,7 @@ export interface JXLEncodeOptions extends EncodeOptions {
562
565
  quality?: number;
563
566
  /**
564
567
  * Compression effort (0-2): higher values usually take longer but may make smaller files. `0` prioritizes speed;
565
- * `2` spends the most time compressing
568
+ * `2` spends the most time compressing (lossy images only: lossless images are encoded the same at `1` and `2`)
566
569
  * @defaultValue `1`
567
570
  */
568
571
  effort?: number;
@@ -741,13 +744,17 @@ export interface ColorToAlphaOptions {
741
744
  /**
742
745
  * An RGBA image; provides the codecs and the manipulation functions. Methods that change the image modify it in place
743
746
  * and return it, so calls can be chained
747
+ *
748
+ * @remarks Subclassing is not supported: the methods that make an image ({@link Image.clone}, {@link Image.extract},
749
+ * {@link Image.decode}, ...) return plain `Image`s, without calling a subclass' constructor
744
750
  */
745
751
  export declare class Image {
746
752
  /**
747
753
  * Creates a new image with the given dimensions, all pixels transparent black
748
754
  * @param width The width in pixels
749
755
  * @param height The height in pixels
750
- * @throws `RangeError` if the width or height is not a number of at least 1, or the image is too large to allocate
756
+ * @throws `TypeError` if the width or height is not a number
757
+ * @throws `RangeError` if the width or height is less than 1, or the image is too large to allocate
751
758
  */
752
759
  constructor(width: number, height: number);
753
760
  /**
@@ -788,7 +795,9 @@ export declare class Image {
788
795
  */
789
796
  get height(): number;
790
797
  /**
791
- * Yields an [x, y, color] array for every pixel in the image (0-based), row by row
798
+ * Yields an [x, y, color] array for every pixel in the image (0-based), row by row. Resizing the image meanwhile
799
+ * doesn't affect the iteration (it goes on over the pixels it started with), but other changes to the pixels, like
800
+ * `setPixelAt()`, are seen by the pixels not yet yielded
792
801
  * @yields The coordinates and color of the pixel ([x, y, color])
793
802
  */
794
803
  pixels(): Generator<[x: number, y: number, color: Color], void, undefined>;
@@ -828,7 +837,7 @@ export declare class Image {
828
837
  /**
829
838
  * Fills the image data with the supplied color
830
839
  * @param color The color, or a function returning the color of each pixel (checked like any color: a result that
831
- * isn't one throws a RangeError)
840
+ * isn't a number throws a TypeError, a number that isn't a color a RangeError)
832
841
  */
833
842
  fill(color: Color | ColorFunction): this;
834
843
  /**
@@ -1123,14 +1132,15 @@ export declare class Image {
1123
1132
  fisheye(options?: FisheyeOptions): this;
1124
1133
  /**
1125
1134
  * Encodes the image into a PNG, with the smallest lossless color type (a palette for up to 256 colors,
1126
- * grayscale or RGB, alpha only if needed). Uses the runtime's native zlib when available
1135
+ * grayscale or RGB, alpha only if needed). Uses the runtime's native zlib when available (the files differ between runtimes, whose zlibs compress differently: about a quarter larger on Deno than on Node and Bun)
1127
1136
  * @param options See {@link PNGEncodeOptions}
1128
1137
  * @return The encoded data
1129
1138
  */
1130
1139
  encodePNG(options?: PNGEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
1131
1140
  /**
1132
1141
  * Encodes the image into a JPEG. JPEG has no transparency: an image with transparent or translucent pixels is
1133
- * composited onto the `background` color (black by default) first, the image itself stays unchanged
1142
+ * composited onto the `background` color (black by default) first, the image itself stays unchanged. An image whose
1143
+ * pixels are all gray is written as a grayscale JPEG (one component)
1134
1144
  * @param options See {@link JPEGEncodeOptions}
1135
1145
  */
1136
1146
  encodeJPEG(options?: JPEGEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
package/dist/image.js CHANGED
@@ -26,7 +26,7 @@ import { encode as utf8 } from "./util/utf8.js";
26
26
  import { resample, BOX, TRIANGLE, CUBIC } from "./util/resample.js";
27
27
  import { gaussianBlur, boxBlurRGBA, premultiply, unpremultiply } from "./util/blur.js";
28
28
  import { Colors, wrapHue, hue2rgb } from "./colors.js";
29
- import { isOptions, checkOptions, finite, nonNegative, positive, unitInterval, oneOf, pixelLimit, checkThreads, gainMapScale, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
29
+ import { isOptions, checkOptions, finite, nonNegative, positive, unitInterval, oneOf, pixelLimit, checkThreads, gainMapEmbed, boolean, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
30
30
  import { MAX_PIXELS, LimitError, decoding, checkGrowth } from "./util/limits.js";
31
31
  import { GainMap } from "./gainmap.js";
32
32
  import * as gain from "./util/gain.js";
@@ -34,6 +34,7 @@ import { multiply, invert } from "./util/matrix.js";
34
34
  import { sampleAffine } from "./util/affine.js";
35
35
  import { rotateBilinear } from "./util/rotate.js";
36
36
  import * as gainMapCodec from "./codecs/gainmap.js";
37
+ import { describe } from "./util/inspect.js";
37
38
  const TRANSFORM_MODES = ['nearest-neighbor', 'bilinear', 'bicubic'];
38
39
  const RESIZE_FITS = ['fill', 'inside', 'contain', 'cover'];
39
40
  const CIRCLE_FITS = ['contain', 'cover'];
@@ -48,6 +49,8 @@ function featureList(features) {
48
49
  throw new RangeError(`Invalid OpenType feature tag: ${JSON.stringify(tag)}`);
49
50
  if (typeof value === 'boolean')
50
51
  return [tag, value ? 1 : 0];
52
+ if (typeof value !== 'number')
53
+ throw new TypeError(`The value of the OpenType feature ${tag} must be a boolean or a number, not ${value === null ? 'null' : typeof value}`);
51
54
  if (!Number.isInteger(value) || value < 0 || value > 255)
52
55
  throw new RangeError(`Invalid value of the OpenType feature ${tag}: ${value}`);
53
56
  return [tag, value];
@@ -113,13 +116,16 @@ export class Image {
113
116
  }
114
117
  *pixels() {
115
118
  const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength);
119
+ const width = this.width, height = this.height;
116
120
  let offset = 0;
117
- for (let y = 0; y < this.height; y++)
118
- for (let x = 0; x < this.width; x++, offset += 4)
121
+ for (let y = 0; y < height; y++)
122
+ for (let x = 0; x < width; x++, offset += 4)
119
123
  yield [x, y, view.getUint32(offset, false)];
120
124
  }
121
125
  static linearGradient(width, height, options) {
122
126
  checkOptions(options, 'Image.linearGradient(100, 50, { stops, angle: 90 })');
127
+ if (options === undefined || options.stops === undefined)
128
+ throw new TypeError('Image.linearGradient(width, height, { stops }) needs the stops in the options');
123
129
  const { stops, angle = 180 } = options;
124
130
  const color = gradientFunction(stops);
125
131
  finite(angle, 'angle');
@@ -138,6 +144,8 @@ export class Image {
138
144
  checkOptions(options, 'Image.radialGradient(100, 50, { stops })');
139
145
  const image = new Image(width, height);
140
146
  ({ width, height } = image);
147
+ if (options === undefined || options.stops === undefined)
148
+ throw new TypeError('Image.radialGradient(width, height, { stops }) needs the stops in the options');
141
149
  const { stops, x: cx = width / 2, y: cy = height / 2, radius = Math.hypot(Math.max(cx, width - cx), Math.max(cy, height - cy)) } = options;
142
150
  const color = gradientFunction(stops);
143
151
  finite(cx, 'x');
@@ -532,7 +540,8 @@ export class Image {
532
540
  return this.__blend__(source, x, y, opacity, blend);
533
541
  const left = Math.max(0, x), top = Math.max(0, y);
534
542
  const right = Math.min(this.width, x + source.width), bottom = Math.min(this.height, y + source.height);
535
- const dst = this.bitmap, src = source.bitmap;
543
+ const dst = this.bitmap;
544
+ const src = source.bitmap.buffer === dst.buffer ? source.bitmap.slice() : source.bitmap;
536
545
  for (let row = top; row < bottom; row++) {
537
546
  for (let column = left, s = 4 * ((row - y) * source.width + left - x), d = 4 * (row * this.width + left); column < right; column++, s += 4, d += 4) {
538
547
  const sa = src[s + 3];
@@ -622,7 +631,8 @@ export class Image {
622
631
  __blend__(source, x, y, opacity, blend) {
623
632
  const left = Math.max(0, x), top = Math.max(0, y);
624
633
  const right = Math.min(this.width, x + source.width), bottom = Math.min(this.height, y + source.height);
625
- const dst = this.bitmap, src = source.bitmap;
634
+ const dst = this.bitmap;
635
+ const src = source.bitmap.buffer === dst.buffer ? source.bitmap.slice() : source.bitmap;
626
636
  for (let row = top; row < bottom; row++) {
627
637
  for (let column = left; column < right; column++) {
628
638
  const s = 4 * ((row - y) * source.width + column - x);
@@ -782,10 +792,12 @@ export class Image {
782
792
  return this;
783
793
  }
784
794
  colorMatrix(matrix) {
785
- if (matrix === null || typeof matrix !== 'object' || (matrix.length !== 9 && matrix.length !== 20))
795
+ if (matrix === null || typeof matrix !== 'object')
796
+ throw new TypeError(`colorMatrix() takes an array of 9 or 20 values, not ${matrix === null ? 'null' : typeof matrix}`);
797
+ if (matrix.length !== 9 && matrix.length !== 20)
786
798
  throw new RangeError('A color matrix has 9 or 20 values');
787
799
  const m = new Float64Array(20);
788
- const value = (v) => finite(typeof v === 'number' ? v : NaN, 'color matrix value');
800
+ const value = (v) => finite(v, 'color matrix value');
789
801
  if (matrix.length === 20)
790
802
  for (let i = 0; i < 20; i++)
791
803
  m[i] = value(matrix[i]);
@@ -809,11 +821,16 @@ export class Image {
809
821
  }
810
822
  transform(matrix, options = {}) {
811
823
  checkOptions(options, 'image.transform([1, 0, 0, 1, 0, 0], { expand: false })');
812
- if (matrix === null || typeof matrix !== 'object' || matrix.length !== 6)
824
+ if (matrix === null || typeof matrix !== 'object')
825
+ throw new TypeError(`transform() takes an array of 6 values, like transform([1, 0, 0, 1, 0, 0]), not ${matrix === null ? 'null' : typeof matrix}`);
826
+ if (matrix.length !== 6)
813
827
  throw new RangeError('A transform has 6 values: [a, b, c, d, e, f]');
814
- const values = Array.from({ length: 6 }, (_, i) => finite(typeof matrix[i] === 'number' ? matrix[i] : NaN, 'transform value'));
828
+ const values = Array.from({ length: 6 }, (_, i) => finite(matrix[i], 'transform value'));
815
829
  const { origin = {}, expand = true, mode = 'bilinear' } = options;
830
+ if (typeof origin !== 'object' || origin === null)
831
+ throw new TypeError(`transform() takes an origin object like { x: 10, y: 20 }, not ${origin === null ? 'null' : typeof origin}`);
816
832
  oneOf(mode, TRANSFORM_MODES, 'transform mode');
833
+ boolean(expand, 'expand');
817
834
  const { x: pivotX = this.width / 2, y: pivotY = this.height / 2 } = origin;
818
835
  finite(pivotX, 'origin x');
819
836
  finite(pivotY, 'origin y');
@@ -850,6 +867,7 @@ export class Image {
850
867
  dropShadow(options = {}) {
851
868
  checkOptions(options, 'image.dropShadow({ blur: 8 })');
852
869
  const { x = 0, y = 0, blur = 0, spread = 0, color = 0x00000080, expand = true } = options;
870
+ boolean(expand, 'expand');
853
871
  finite(x, 'x');
854
872
  finite(y, 'y');
855
873
  if (finite(blur, 'blur') < 0)
@@ -891,6 +909,7 @@ export class Image {
891
909
  outline(options = {}) {
892
910
  checkOptions(options, 'image.outline({ width: 4 })');
893
911
  const { width = 1, color = 0x000000ff, expand = true } = options;
912
+ boolean(expand, 'expand');
894
913
  if (finite(width, 'outline width') < 0)
895
914
  throw new RangeError('Invalid outline width');
896
915
  const [r, g, b, a] = Colors.toRGBA(checkColor(color));
@@ -1059,7 +1078,11 @@ export class Image {
1059
1078
  dominantColor(options = {}) {
1060
1079
  checkOptions(options, 'dominantColor({ ignoreBlack: false })');
1061
1080
  const { ignoreBlack = true, ignoreWhite = true, threshold: bwThreshold = 60 } = options;
1062
- const threshold = Math.min(256, Math.max(0, finite(bwThreshold, 'threshold')));
1081
+ boolean(ignoreBlack, 'ignoreBlack');
1082
+ boolean(ignoreWhite, 'ignoreWhite');
1083
+ const threshold = finite(bwThreshold, 'threshold');
1084
+ if (threshold < 0 || threshold > 256)
1085
+ throw new RangeError(`threshold has to be between 0 and 256, not ${threshold}`);
1063
1086
  const pixels = this.__bytes__();
1064
1087
  const color = quantize.dominantColor(pixels, (r, g, b) => !(ignoreBlack && Math.max(r, g, b) < threshold) && !(ignoreWhite && Math.min(r, g, b) > 255 - threshold))
1065
1088
  || quantize.dominantColor(pixels, () => true);
@@ -1069,6 +1092,7 @@ export class Image {
1069
1092
  checkOptions(options, 'rotate(angle, { expand: false })');
1070
1093
  const { expand = true, mode = 'bilinear' } = options;
1071
1094
  oneOf(mode, TRANSFORM_MODES, 'rotate mode');
1095
+ boolean(expand, 'expand');
1072
1096
  angle = ((-finite(angle, 'angle') % 360) + 360) % 360;
1073
1097
  if (angle === 0)
1074
1098
  return this;
@@ -1245,24 +1269,31 @@ export class Image {
1245
1269
  if (subsampling !== undefined)
1246
1270
  oneOf(subsampling, SUBSAMPLINGS, 'subsampling');
1247
1271
  const backgroundColor = checkColor(background, 'background');
1272
+ const embed = gainMapEmbed(gainMapOption);
1248
1273
  const m = resolveMetadata(metadata);
1249
- const base = { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined, subsampling };
1250
- const source = this.__flattened__(backgroundColor, gainMapOption !== false) ?? this;
1274
+ const source = this.__flattened__(backgroundColor, embed !== null) ?? this;
1251
1275
  const gainMap = source.__gain_map__;
1252
- if (!gainMap || gainMapOption === false)
1276
+ const base = { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined, subsampling, gray: source.__is_gray__() };
1277
+ if (!gainMap || !embed)
1253
1278
  return jpeg.encode(source.__bytes__(), source.width, source.height, quality, base);
1254
- const { quality: mapQuality, scale } = typeof gainMapOption === 'object' && gainMapOption !== null ? gainMapOption : {};
1279
+ const { quality: mapQuality, scale } = embed;
1255
1280
  let width, height;
1256
1281
  if (scale !== undefined) {
1257
- const s = gainMapScale(scale);
1258
- width = Math.max(1, Math.round(this.width * s));
1259
- height = Math.max(1, Math.round(this.height * s));
1282
+ width = Math.max(1, Math.round(this.width * scale));
1283
+ height = Math.max(1, Math.round(this.height * scale));
1260
1284
  }
1261
1285
  const params = gainMap.__params__();
1262
- const map = gainMapCodec.mapWithMetadata(gainMap.__body__(mapQuality === undefined ? undefined : Math.max(1, checkQuality(mapQuality, 'gain map quality')), width, height), params);
1286
+ const map = gainMapCodec.mapWithMetadata(gainMap.__body__(mapQuality, width, height), params);
1263
1287
  const primary = jpeg.encode(source.__bytes__(), source.width, source.height, quality, { ...base, segments: gainMapCodec.primarySegments(map.length) });
1264
1288
  return gainMapCodec.finish(primary, map);
1265
1289
  }
1290
+ __is_gray__() {
1291
+ const px = this.bitmap;
1292
+ for (let i = 0; i < px.length; i += 4)
1293
+ if (px[i] !== px[i + 1] || px[i] !== px[i + 2])
1294
+ return false;
1295
+ return true;
1296
+ }
1266
1297
  __flattened__(background, withGainMap) {
1267
1298
  const pixels = this.bitmap;
1268
1299
  let opaque = true;
@@ -1320,15 +1351,14 @@ export class Image {
1320
1351
  });
1321
1352
  }
1322
1353
  __gain_map_pixels__(option) {
1354
+ const embed = gainMapEmbed(option);
1323
1355
  const gainMap = this.__gain_map__;
1324
- if (!gainMap || option === false)
1356
+ if (!gainMap || !embed)
1325
1357
  return undefined;
1326
- const { quality = 90, scale } = typeof option === 'object' && option !== null ? option : {};
1327
- const mapQuality = Math.max(1, checkQuality(quality, 'gain map quality'));
1358
+ const { quality: mapQuality = 90, scale } = embed;
1328
1359
  let map = gainMap.image;
1329
1360
  if (scale !== undefined) {
1330
- const s = gainMapScale(scale);
1331
- const width = Math.max(1, Math.round(this.width * s)), height = Math.max(1, Math.round(this.height * s));
1361
+ const width = Math.max(1, Math.round(this.width * scale)), height = Math.max(1, Math.round(this.height * scale));
1332
1362
  if (width !== map.width || height !== map.height)
1333
1363
  map = map.clone().resize(width, height);
1334
1364
  }
@@ -1353,6 +1383,9 @@ export class Image {
1353
1383
  checkThreads(threads);
1354
1384
  pixelLimit(maxPixels);
1355
1385
  oneOf(toneMapping, TONE_MAPPINGS, 'toneMapping');
1386
+ boolean(applyOrientation, 'applyOrientation');
1387
+ boolean(applyColorProfile, 'applyColorProfile');
1388
+ boolean(gainMap, 'gainMap');
1356
1389
  const data = view(input);
1357
1390
  const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
1358
1391
  const decoded = await decoding(() => {
@@ -1495,7 +1528,7 @@ export class Image {
1495
1528
  if (sizes > 1)
1496
1529
  throw new TypeError('renderSVG() takes one of width, height and scale');
1497
1530
  const mode = givenWidth !== undefined ? 'width' : givenHeight !== undefined ? 'height' : 'scale';
1498
- const size = finite(givenWidth ?? givenHeight ?? scale ?? 1, `SVG ${mode}`);
1531
+ const size = finite(mode === 'width' ? givenWidth : mode === 'height' ? givenHeight : scale === undefined ? 1 : scale, `SVG ${mode}`);
1499
1532
  if (mode === 'scale' && size <= 0)
1500
1533
  throw new RangeError('SVG scale must be > 0');
1501
1534
  if (mode !== 'scale' && size < 1)
@@ -1555,6 +1588,7 @@ export class Image {
1555
1588
  throw new TypeError('renderText(text, options) needs the font in the options');
1556
1589
  const { font, color = 0xffffffff, strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {}, maxPixels = MAX_PIXELS } = options;
1557
1590
  pixelLimit(maxPixels);
1591
+ boolean(hinting, 'hinting');
1558
1592
  const { width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign } = options;
1559
1593
  const layout = textLayout({ width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign });
1560
1594
  const axes = textRenderer.axisValues(variations);
@@ -1797,3 +1831,4 @@ function distanceTransform(f, n, d, v, z, nearest) {
1797
1831
  nearest[q] = v[j];
1798
1832
  }
1799
1833
  }
1834
+ describe(Image, image => ({ width: image.width, height: image.height }));
@@ -9,6 +9,9 @@
9
9
  * | GIF | software, comment (comment extensions) |
10
10
  * | TGA | author, comment, creation time, software (extension area) |
11
11
  *
12
+ * The Exif and TGA text fields are ASCII in the file format; other characters are written as UTF-8, which readers
13
+ * that follow the format show wrongly. PNG text chunks take any text.
14
+ *
12
15
  * Empty fields (and `null` ones) are left out. Without metadata, the files only say which software made them (`software`), so the same
13
16
  * image always encodes to the same bytes
14
17
  */
package/dist/metadata.js CHANGED
@@ -2,7 +2,9 @@ import { encode as utf8 } from "./util/utf8.js";
2
2
  import * as exif from "./codecs/exif.js";
3
3
  const TEXT_FIELDS = ['title', 'author', 'description', 'copyright', 'software', 'disclaimer', 'warning', 'source', 'comment'];
4
4
  export function resolveMetadata(metadata = {}) {
5
- const { creationTime, software } = metadata || {};
5
+ if (metadata === null || typeof metadata !== 'object' || Array.isArray(metadata))
6
+ throw new TypeError(`metadata takes an object, like { title: 'Sunset' }, not ${metadata === null ? 'null' : Array.isArray(metadata) ? 'an array' : typeof metadata}`);
7
+ const { creationTime, software } = metadata;
6
8
  const resolved = {};
7
9
  if (creationTime !== undefined && creationTime !== null) {
8
10
  const time = new Date(creationTime);
@@ -11,9 +13,12 @@ export function resolveMetadata(metadata = {}) {
11
13
  resolved.creationTime = time;
12
14
  }
13
15
  for (const key of TEXT_FIELDS) {
14
- const value = key === 'software' && software === undefined ? 'ImageScript' : metadata?.[key];
15
- if (value)
16
- resolved[key] = String(value);
16
+ const value = key === 'software' && software === undefined ? 'ImageScript' : metadata[key];
17
+ if (value === undefined || value === null || value === '')
18
+ continue;
19
+ if (typeof value !== 'string')
20
+ throw new TypeError(`metadata ${key} must be a string, not ${typeof value}`);
21
+ resolved[key] = value;
17
22
  }
18
23
  return resolved;
19
24
  }
@@ -32,6 +37,8 @@ export function pngText(m) {
32
37
  };
33
38
  }
34
39
  export function exifData(m) {
40
+ if (!m.description && !m.software && !m.creationTime && !m.author && !m.copyright)
41
+ return undefined;
35
42
  return exif.encode({
36
43
  description: m.description,
37
44
  software: m.software,
@@ -107,7 +107,11 @@ function documentSize(root) {
107
107
  return fallback * parseFloat(value) / 100;
108
108
  return parseLength(value, null, 16);
109
109
  };
110
- return { width: lengthOf(root.attrs.width, viewBox ? viewBox[2] : 100), height: lengthOf(root.attrs.height, viewBox ? viewBox[3] : 100) };
110
+ const width = lengthOf(root.attrs.width, viewBox ? viewBox[2] : 100), height = lengthOf(root.attrs.height, viewBox ? viewBox[3] : 100);
111
+ const given = (value) => value !== undefined && value !== 'auto';
112
+ if (viewBox && viewBox[2] > 0 && viewBox[3] > 0 && given(root.attrs.width) !== given(root.attrs.height))
113
+ return given(root.attrs.width) ? { width, height: width * viewBox[3] / viewBox[2] } : { width: height * viewBox[2] / viewBox[3], height };
114
+ return { width, height };
111
115
  }
112
116
  const glyphDocuments = new WeakMap();
113
117
  function drawRaster(layer, image, matrix, filter) {
@@ -39,7 +39,9 @@ export function axisValues(variations) {
39
39
  if (!tag)
40
40
  throw new RangeError(`Unknown font variation ${key}: use weight, width, slant, italic, opticalSize or an axis tag`);
41
41
  const v = typeof value === 'boolean' ? +value : value;
42
- if (typeof v !== 'number' || !Number.isFinite(v))
42
+ if (typeof v !== 'number')
43
+ throw new TypeError(`The font variation ${key} must be a number or a boolean, not ${v === null ? 'null' : typeof v}`);
44
+ if (!Number.isFinite(v))
43
45
  throw new RangeError(`Invalid font variation ${key}: ${String(value)}`);
44
46
  values[tag] = v;
45
47
  }
@@ -143,8 +145,8 @@ async function layOut(fonts, size, text, layout, hinting, foreground, features,
143
145
  const coverage = new Uint8Array(width * height);
144
146
  let color = null;
145
147
  for (const [n, line] of visible.entries()) {
146
- let offset = layout.horizontalAlign === 'right' ? width - line.extent
147
- : layout.horizontalAlign === 'center' ? (width - line.extent) / 2 : 0;
148
+ const align = layout.horizontalAlign ?? (line.rtl ? 'right' : 'left');
149
+ let offset = align === 'right' ? width - line.extent : align === 'center' ? (width - line.extent - line.start) / 2 : -line.start;
148
150
  if (primary.hinter)
149
151
  offset = Math.round(offset);
150
152
  const baseline = top + ascent + n * lineHeight;
@@ -287,8 +289,9 @@ function shapeRange(p, start, end, levels, font, size, features) {
287
289
  const isSpace = (codepoint) => codepoint === 0x20 || codepoint === 0x09 || codepoint === 0x3000 || codepoint >= 0x2000 && codepoint <= 0x200a;
288
290
  function layOutParagraph(p, layout, font, size, features) {
289
291
  const n = p.codepoints.length;
292
+ const rtl = (p.bidi.level & 1) === 1;
290
293
  if (!n)
291
- return [{ glyphs: [], extent: 0 }];
294
+ return [{ glyphs: [], extent: 0, start: 0, rtl }];
292
295
  const whole = shapeRange(p, 0, n, p.bidi.levels, font, size, features);
293
296
  const width = new Float64Array(n), starts = new Uint8Array(n + 1);
294
297
  starts[n] = 1;
@@ -336,11 +339,13 @@ function layOutParagraph(p, layout, font, size, features) {
336
339
  const shifted = new Int8Array(n);
337
340
  shifted.set(levels, start);
338
341
  const { glyphs } = ranges.length === 1 ? whole : shapeRange(p, start, end, shifted, font, size, features);
339
- let extent = 0;
342
+ let extent = 0, left = Infinity;
340
343
  for (const { x, dx, glyph } of glyphs)
341
- if (glyph.ink)
344
+ if (glyph.ink) {
342
345
  extent = Math.max(extent, x + dx + glyph.ink.right);
343
- return { glyphs, extent };
346
+ left = Math.min(left, x + dx + glyph.ink.left);
347
+ }
348
+ return { glyphs, extent, start: rtl && left < Infinity ? Math.max(0, left) : 0, rtl };
344
349
  });
345
350
  }
346
351
  async function scaledBitmap(glyph, scale) {
@@ -25,7 +25,8 @@ export interface TextLayoutOptions {
25
25
  /**
26
26
  * Where the lines are placed horizontally: `'left'`, `'center'` or `'right'` in the `width`, or (without one)
27
27
  * relative to the widest line
28
- * @defaultValue `'left'`
28
+ * @defaultValue The paragraph's direction: `'left'` for left-to-right text, `'right'` for right-to-left text
29
+ * (Arabic, Hebrew, ...), like the `start` of CSS' `text-align`
29
30
  */
30
31
  horizontalAlign?: HorizontalAlign;
31
32
  /**
@@ -1,12 +1,13 @@
1
- import { oneOf } from "./util/options.js";
1
+ import { oneOf, checkNumber } from "./util/options.js";
2
2
  const HORIZONTAL = ['left', 'center', 'right'];
3
3
  const VERTICAL = ['top', 'middle', 'bottom'];
4
4
  function boxSide(value, name) {
5
5
  if (value === undefined)
6
6
  return undefined;
7
- const side = Math.floor(Number(value));
8
- if (typeof value !== 'number' || !(side >= 1) || !Number.isFinite(side))
9
- throw new RangeError(`${name} must be a finite number from 1, not ${String(value)}`);
7
+ checkNumber(value, name);
8
+ const side = Math.floor(value);
9
+ if (!(side >= 1) || !Number.isFinite(side))
10
+ throw new RangeError(`${name} must be a finite number from 1, not ${value}`);
10
11
  return side;
11
12
  }
12
13
  export function textLayout(options) {
@@ -15,7 +16,7 @@ export function textLayout(options) {
15
16
  width: boxSide(width, 'width'),
16
17
  height: boxSide(height, 'height'),
17
18
  wrapStyle: wrapStyle === undefined ? 'word' : oneOf(wrapStyle, ['word', 'char'], 'wrapStyle'),
18
- horizontalAlign: horizontalAlign === undefined ? 'left' : oneOf(horizontalAlign, HORIZONTAL, 'horizontalAlign'),
19
+ horizontalAlign: horizontalAlign === undefined ? undefined : oneOf(horizontalAlign, HORIZONTAL, 'horizontalAlign'),
19
20
  verticalAlign: verticalAlign === undefined ? 'top' : oneOf(verticalAlign, VERTICAL, 'verticalAlign')
20
21
  };
21
22
  }
@@ -0,0 +1,16 @@
1
+ export function describe(type, json) {
2
+ Object.defineProperty(type.prototype, Symbol.for('nodejs.util.inspect.custom'), {
3
+ value() {
4
+ return this.toString();
5
+ },
6
+ writable: true,
7
+ configurable: true
8
+ });
9
+ Object.defineProperty(type.prototype, 'toJSON', {
10
+ value() {
11
+ return json(this);
12
+ },
13
+ writable: true,
14
+ configurable: true
15
+ });
16
+ }
package/dist/util/mem.js CHANGED
@@ -7,7 +7,7 @@ export function view(buffer) {
7
7
  return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
8
8
  if (typeof SharedArrayBuffer !== 'undefined' && buffer instanceof SharedArrayBuffer)
9
9
  return new Uint8Array(buffer);
10
- throw new TypeError('The provided value is not of type \'(ArrayBuffer or ArrayBufferView)\'');
10
+ throw new TypeError(`Binary data has to be an ArrayBuffer or a typed array like Uint8Array, not ${buffer === null ? 'null' : typeof buffer}`);
11
11
  }
12
12
  export function concat(parts) {
13
13
  let length = 0;
@@ -1,21 +1,39 @@
1
+ export function shown(value) {
2
+ if (value === null)
3
+ return 'null';
4
+ if (Array.isArray(value))
5
+ return 'an array';
6
+ if (typeof value === 'string')
7
+ return `'${value}'`;
8
+ if (typeof value === 'number')
9
+ return String(value);
10
+ if (typeof value === 'object')
11
+ return 'an object';
12
+ return typeof value;
13
+ }
1
14
  export function isOptions(value) {
2
- return typeof value === 'object' && value !== null && !ArrayBuffer.isView(value);
15
+ return typeof value === 'object' && value !== null && !Array.isArray(value) && !ArrayBuffer.isView(value);
3
16
  }
4
17
  export function checkOptions(value, usage) {
5
18
  if (value !== undefined && !isOptions(value))
6
- throw new TypeError(`${usage.split('(')[0]}() takes an options object, like ${usage}, not ${value === null ? 'null' : typeof value}`);
19
+ throw new TypeError(`${usage.split('(')[0]}() takes an options object, like ${usage}, not ${shown(value)}`);
7
20
  }
8
21
  export function oneOf(value, allowed, name) {
9
22
  if (typeof value !== 'string' || !allowed.includes(value)) {
10
23
  const list = allowed.map(a => `'${a}'`);
11
24
  const expected = list.length > 1 ? `${list.slice(0, -1).join(', ')} or ${list[list.length - 1]}` : list[0];
12
- throw new TypeError(`${name} must be ${expected}, not ${typeof value === 'string' ? `'${value}'` : String(value)}`);
25
+ throw new TypeError(`${name} must be ${expected}, not ${shown(value)}`);
13
26
  }
14
27
  return value;
15
28
  }
29
+ export function boolean(value, name) {
30
+ if (typeof value !== 'boolean')
31
+ throw new TypeError(`${name} must be true or false, not ${shown(value)}`);
32
+ return value;
33
+ }
16
34
  export function checkNumber(value, name) {
17
35
  if (typeof value !== 'number')
18
- throw new TypeError(`${name} must be a number, not ${value === null ? 'null' : typeof value}`);
36
+ throw new TypeError(`${name} must be a number, not ${shown(value)}`);
19
37
  }
20
38
  export function finite(value, name) {
21
39
  checkNumber(value, name);
@@ -25,7 +43,7 @@ export function finite(value, name) {
25
43
  }
26
44
  export function loopCount(value, name = 'loop count') {
27
45
  if (typeof value !== 'number')
28
- throw new TypeError(`${name} must be a number (Infinity or an integer from 0), not ${value === null ? 'null' : typeof value}`);
46
+ throw new TypeError(`${name} must be a number (Infinity or an integer from 0), not ${shown(value)}`);
29
47
  if (value !== Infinity && (!Number.isInteger(value) || value < 0))
30
48
  throw new RangeError(`${name} must be Infinity or an integer from 0, not ${value}`);
31
49
  return value;
@@ -77,6 +95,24 @@ export function pixelLimit(value, name = 'maxPixels') {
77
95
  throw new RangeError(`${name} must be a positive number, not ${value}`);
78
96
  return value;
79
97
  }
98
+ export function gainMapEmbed(value) {
99
+ if (value === false)
100
+ return null;
101
+ if (value === true)
102
+ return {};
103
+ if (typeof value !== 'object' || value === null)
104
+ throw new TypeError(`gainMap must be true, false or an options object like { quality: 90, scale: 0.5 }, not ${shown(value)}`);
105
+ const { quality: q, scale } = value;
106
+ const options = {};
107
+ if (q !== undefined) {
108
+ options.quality = quality(q, 'gain map quality');
109
+ if (options.quality < 1)
110
+ throw new RangeError(`gain map quality must be 1-100, not ${options.quality}`);
111
+ }
112
+ if (scale !== undefined)
113
+ options.scale = gainMapScale(scale);
114
+ return options;
115
+ }
80
116
  export function gainMapScale(value) {
81
117
  const scale = finite(value, 'gain map scale');
82
118
  if (!(scale > 0 && scale <= 1))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "imagescript",
3
- "version": "4.0.0-rc.4",
3
+ "version": "4.0.0-rc.5",
4
4
  "description": "Pure TypeScript image processing that runs everywhere",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",