imagescript 3.13.2 → 3.14.0

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.
@@ -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 { finite } from "../util/options.js";
11
+ import { effort as checkEffort, quality as checkQuality } 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');
@@ -289,15 +289,10 @@ export async function encode(rgba, width, height, exif, threads = 1) {
289
289
  return riff([riffChunk('VP8X', vp8x), bitstream, riffChunk('EXIF', exif)]);
290
290
  }
291
291
  export function lossyOptions(quality, effort, sharp, alphaQuality) {
292
+ checkEffort(effort, 6);
292
293
  if (quality === undefined)
293
294
  return undefined;
294
- const q = finite(quality, 'quality'), a = finite(alphaQuality, 'alphaQuality');
295
- if (q < 0 || q > 100)
296
- throw new RangeError(`quality must be 0-100, not ${q}`);
297
- if (a < 0 || a > 100)
298
- throw new RangeError(`alphaQuality must be 0-100, not ${a}`);
299
- if (!Number.isInteger(effort) || effort < 0 || effort > 6)
300
- throw new RangeError(`effort must be an integer 0-6, not ${effort}`);
295
+ const q = checkQuality(quality), a = checkQuality(alphaQuality, 'alphaQuality');
301
296
  return { quality: q, method: effort, sharp, alphaQuality: Math.round(a) };
302
297
  }
303
298
  export async function encodeLossy(rgba, width, height, lossy, exif) {
package/dist/image.d.ts CHANGED
@@ -184,16 +184,19 @@ export interface JXLEncodeOptions {
184
184
  */
185
185
  quality?: number;
186
186
  /**
187
- * How hard lossy compression searches for the best transforms: 0-2, faster to smaller. 0 uses 8x8 DCTs only (like
188
- * `cjxl -e 3`), 1 and 2 search their sizes like `cjxl -e 5` (2 tries more of the small ones), and 2 also stores
189
- * text-like features that repeat (the glyphs of screenshots) once, as patches like `cjxl -e 7`. Default: `1`
187
+ * How hard compression works: 0-2, faster to smaller. Lossy: 0 uses 8x8 DCTs only (like `cjxl -e 3`), 1 and 2
188
+ * search their sizes like `cjxl -e 5` (2 tries more of the small ones), and 2 also stores text-like features that
189
+ * repeat (the glyphs of screenshots) once, as patches like `cjxl -e 7`. Lossless: 0 is `cjxl -e 1`'s fast mode
190
+ * (byte for byte), 1 and 2 like `cjxl -e 3` (about 15% smaller for photos, 13% for graphics; a few times slower).
191
+ * Default: `1`
190
192
  */
191
193
  effort?: number;
192
194
  /**
193
- * At most this many worker threads compress lossily in parallel (the same file, faster: 2.6 times with 8 on a
194
- * 1920x1080 photo at effort 1, 4.2 times on 3840x2160), `1` for none. Small images (under about 1.5 megapixels at
195
- * effort 0, 512x512 pixels at 1, 384x384 at 2), and runtimes whose workers can't share memory (browsers without
196
- * cross-origin isolation) encode without them.
195
+ * At most this many worker threads compress in parallel (the same file, faster: lossy 2.3 times with 8 on a
196
+ * 1920x1080 photo at effort 1, 3.8 times on 3840x2160; lossless 2.8 and 4.3 times), `1` for none. Small images
197
+ * (lossy under about 1.5 megapixels at effort 0, 512x512 pixels at 1, 384x384 at 2; lossless under 724x724 and
198
+ * always at effort 0), and runtimes whose workers can't share memory (browsers without cross-origin isolation)
199
+ * encode without them.
197
200
  * Default: the processors available, at most 8
198
201
  */
199
202
  threads?: number;
@@ -873,11 +876,13 @@ export declare class Image {
873
876
  */
874
877
  encodeAVIF({ quality, alphaQuality, subsampling, effort, threads, metadata }?: AVIFEncodeOptions): Promise<Uint8Array>;
875
878
  /**
876
- * Encodes the image as JPEG XL: losslessly (the default), the codestream byte for byte like libjxl's `cjxl -e 1` on
877
- * CPUs with AVX2 or NEON (its fast lossless mode: the gradient predictor, a palette if the image has at most 511
878
- * colors besides black, else YCoCg; greyscale if the image is), or lossy with a quality (like `cjxl -q`: XYB,
879
- * varblocks of libjxl's search, chroma from luma, the edge preserving filter). Alpha (if the image has
880
- * transparency) is lossless either way. The codestream is in the container, with the metadata as Exif
879
+ * Encodes the image as JPEG XL: losslessly (the default) like libjxl's `cjxl -e 3` (a palette of up to 1024 colors,
880
+ * else palettes of channels using few of their values; YCoCg; the weighted predictor in contexts of its error;
881
+ * greyscale if the image is), at effort 0 the codestream byte for byte like `cjxl -e 1` on CPUs with AVX2 or NEON
882
+ * (its fast lossless mode: the gradient predictor, a palette if the image has at most 511 colors besides black,
883
+ * else YCoCg), or lossy with a quality (like `cjxl -q`: XYB, varblocks of libjxl's search, chroma from luma, the
884
+ * edge preserving filter). Alpha (if the image has transparency) is lossless either way. The codestream is in the
885
+ * container, with the metadata as Exif
881
886
  * @param options See {@link JXLEncodeOptions}
882
887
  */
883
888
  encodeJXL({ quality, effort, threads, metadata }?: JXLEncodeOptions): Promise<Uint8Array>;
package/dist/image.js CHANGED
@@ -30,7 +30,7 @@ import { encode as utf8 } from "./util/utf8.js";
30
30
  import { resample, BOX, TRIANGLE, CUBIC } from "./util/resample.js";
31
31
  import { rotateBilinear } from "./util/rotate.js";
32
32
  import { gaussianBlur, boxBlurRGBA, premultiply, unpremultiply } from "./util/blur.js";
33
- import { isOptions, finite, color as checkColor } from "./util/options.js";
33
+ import { isOptions, finite, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
34
34
  import { MAX_PIXELS, decoding } from "./util/limits.js";
35
35
  function featureList(features) {
36
36
  if (typeof features !== 'object' || features === null)
@@ -790,7 +790,7 @@ export class Image {
790
790
  dominantColor(ignoreBlackOrOptions = true, ignoreWhiteArgument = true, thresholdArgument = 0xf) {
791
791
  const { ignoreBlack = true, ignoreWhite = true, threshold: bwThreshold = 0xf } = typeof ignoreBlackOrOptions === 'object' && ignoreBlackOrOptions !== null
792
792
  ? ignoreBlackOrOptions : { ignoreBlack: ignoreBlackOrOptions, ignoreWhite: ignoreWhiteArgument, threshold: thresholdArgument };
793
- const threshold = Math.min(64, Math.max(0, bwThreshold)) * 4;
793
+ const threshold = Math.min(64, Math.max(0, finite(bwThreshold, 'threshold'))) * 4;
794
794
  const pixels = this.__bytes__();
795
795
  const color = quantize.dominantColor(pixels, (r, g, b) => !(ignoreBlack && Math.max(r, g, b) < threshold) && !(ignoreWhite && Math.min(r, g, b) > 255 - threshold))
796
796
  || quantize.dominantColor(pixels, () => true);
@@ -1021,8 +1021,7 @@ export class Image {
1021
1021
  ({ compression = 4, metadata = {} } = compressionOrOptions);
1022
1022
  else
1023
1023
  metadata = compressionOrOptions;
1024
- const level = Math.min(9, Math.max(0, ~~finite(compression, 'compression level')));
1025
- return png.encodeRGBA(this.__bytes__(), this.width, this.height, level, pngText(resolveMetadata(metadata)));
1024
+ return png.encodeRGBA(this.__bytes__(), this.width, this.height, compressionLevel(compression), pngText(resolveMetadata(metadata)));
1026
1025
  }
1027
1026
  encodePNG(compressionOrOptions, metadata) {
1028
1027
  return this.encode(compressionOrOptions, metadata);
@@ -1051,19 +1050,19 @@ export class Image {
1051
1050
  return qoi.encode(this.__bytes__(), this.width, this.height);
1052
1051
  }
1053
1052
  async encodeAVIF({ quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1, threads = defaultThreads(), metadata = {} } = {}) {
1053
+ checkEffort(effort, 2);
1054
1054
  checkThreads(threads);
1055
+ if (subsampling !== '4:4:4' && subsampling !== '4:2:0')
1056
+ throw new TypeError(`subsampling must be '4:4:4' or '4:2:0', not ${String(subsampling)}`);
1055
1057
  const exif = exifData(resolveMetadata(metadata));
1056
- return avifEnc.encode(this.__bytes__(), this.width, this.height, { quality: finite(quality, 'quality'), alphaQuality: finite(alphaQuality, 'alphaQuality'), subsampling, effort, exif, threads });
1058
+ return avifEnc.encode(this.__bytes__(), this.width, this.height, { quality: checkQuality(quality), alphaQuality: checkQuality(alphaQuality, 'alphaQuality'), subsampling, effort, exif, threads });
1057
1059
  }
1058
1060
  async encodeJXL({ quality, effort = 1, threads = defaultThreads(), metadata = {} } = {}) {
1059
- if (!Number.isInteger(effort) || effort < 0 || effort > 2)
1060
- throw new RangeError(`effort must be an integer 0-2, not ${effort}`);
1061
+ checkEffort(effort, 2);
1061
1062
  checkThreads(threads);
1062
1063
  let distance = 0;
1063
1064
  if (quality !== undefined) {
1064
- const q = finite(quality, 'quality');
1065
- if (q < 0 || q > 100)
1066
- throw new RangeError(`quality must be 0-100, not ${q}`);
1065
+ const q = checkQuality(quality);
1067
1066
  distance = q >= 100 ? 0 : q >= 30 ? 0.1 + (100 - q) * 0.09 : 53 / 3000 * q * q - 23 / 20 * q + 25;
1068
1067
  }
1069
1068
  return jxl.encode(this.__bytes__(), this.width, this.height, exifData(resolveMetadata(metadata)), distance, effort, threads);
@@ -1074,6 +1073,8 @@ export class Image {
1074
1073
  static async decode(input, options = {}) {
1075
1074
  const { applyOrientation = true, applyColorProfile = true, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = defaultThreads() } = options;
1076
1075
  checkThreads(threads);
1076
+ if (!(Number(maxPixels) > 0))
1077
+ throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
1077
1078
  if (toneMapping !== 'reinhard' && toneMapping !== 'clamp')
1078
1079
  throw new TypeError(`toneMapping must be 'reinhard' or 'clamp', not ${String(toneMapping)}`);
1079
1080
  const data = view(input);
@@ -1112,6 +1113,8 @@ export class Image {
1112
1113
  return hdr.decode(data, maxPixels, toneMapping);
1113
1114
  if (ImageType.isTGA(dataView))
1114
1115
  return tga.decode(data, maxPixels);
1116
+ if (ImageType.isGIF(dataView))
1117
+ throw new Error('GIFs have to be decoded with Animation.decode() (or decode(), which returns an image or an animation)');
1115
1118
  throw new Error('Unsupported image type');
1116
1119
  });
1117
1120
  if (applyColorProfile) {
@@ -1181,6 +1184,7 @@ export class Image {
1181
1184
  const { size = 1, mode = Image.SVG_MODE_SCALE, fonts = [] } = isOptions(sizeOrOptions) ? sizeOrOptions : { size: sizeOrOptions, mode: modeArgument };
1182
1185
  if (![1, 2, 3].includes(mode))
1183
1186
  throw new Error('Invalid SVG scaling mode');
1187
+ finite(size, 'SVG size');
1184
1188
  if (mode === Image.SVG_MODE_SCALE && size <= 0)
1185
1189
  throw new RangeError('SVG scale must be > 0');
1186
1190
  if (mode !== Image.SVG_MODE_SCALE && size < 1)
@@ -1213,6 +1217,8 @@ export class Image {
1213
1217
  const { color = 0xffffffff, layout = new TextLayout(), strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {} } = options;
1214
1218
  const axes = textRenderer.axisValues(variations);
1215
1219
  size = finite(size, 'font size');
1220
+ if (size < 0)
1221
+ throw new RangeError(`Invalid font size: ${size}`);
1216
1222
  if (finite(strokeWidth, 'stroke width') < 0)
1217
1223
  throw new RangeError('Invalid stroke width');
1218
1224
  const fonts = Array.isArray(font) ? font : [font];
@@ -334,11 +334,15 @@ function apply(kind, linear, ts, region, subregion, input) {
334
334
  const pixmap = create(region.width, region.height);
335
335
  const sx = kind.scale * scaleX, sy = kind.scale * scaleY, w = src.width, h = src.height;
336
336
  const round = (v) => Math.sign(v) * Math.round(Math.abs(v));
337
+ const channel = (m, c) => {
338
+ const a = map.data[m + 3];
339
+ return c === 3 ? a / 255 : a ? map.data[m + c] / a : 0;
340
+ };
337
341
  for (let y = 0; y < Math.min(h, map.height); y++)
338
342
  for (let x = 0; x < Math.min(w, map.width); x++) {
339
343
  const m = (y * map.width + x) * 4;
340
- const ox = round(x + (map.data[m + kind.xChannel] / 255 - 0.5) * sx * kind.scale);
341
- const oy = round(y + (map.data[m + kind.yChannel] / 255 - 0.5) * sy * kind.scale);
344
+ const ox = round(x + (channel(m, kind.xChannel) - 0.5) * sx);
345
+ const oy = round(y + (channel(m, kind.yChannel) - 0.5) * sy);
342
346
  if (ox < 0 || ox >= w || oy < 0 || oy >= h)
343
347
  continue;
344
348
  pixmap.data.set(src.data.subarray((oy * w + ox) * 4, (oy * w + ox) * 4 + 4), (y * pixmap.width + x) * 4);
@@ -7,4 +7,16 @@ export function finite(value, name) {
7
7
  throw new RangeError(`Invalid ${name}: ${value}`);
8
8
  return number;
9
9
  }
10
+ export function quality(value, name = 'quality') {
11
+ const q = finite(value, name);
12
+ if (q < 0 || q > 100)
13
+ throw new RangeError(`${name} must be 0-100, not ${q}`);
14
+ return q;
15
+ }
16
+ export function effort(value, max) {
17
+ if (!Number.isInteger(value) || value < 0 || value > max)
18
+ throw new RangeError(`effort must be an integer 0-${max}, not ${value}`);
19
+ return value;
20
+ }
21
+ export const compressionLevel = (value) => Math.min(9, Math.max(0, ~~finite(value, 'compression level')));
10
22
  export const color = (value, name = 'color') => finite(value, name);
@@ -5,6 +5,7 @@ import { varblockChunks } from "../codecs/jxl/acs-enc.js";
5
5
  import { maskBlurChunks, maskingChunks } from "../codecs/jxl/aq-enc.js";
6
6
  import { coefficientChunks, hfTokenChunks, xybChunks } from "../codecs/jxl/vardct-enc.js";
7
7
  import { groupChunks, postChunks } from "../codecs/jxl/frame.js";
8
+ import { modularGroupChunks, modularWriteChunks } from "../codecs/jxl/modular-lossless.js";
8
9
  const chunkTasks = {
9
10
  'avif-convert': conversionChunks,
10
11
  'avif-tiles': tileChunks,
@@ -16,6 +17,8 @@ const chunkTasks = {
16
17
  'jxl-varblocks': varblockChunks,
17
18
  'jxl-coefficients': coefficientChunks,
18
19
  'jxl-hf-tokens': hfTokenChunks,
20
+ 'jxl-modular-groups': modularGroupChunks,
21
+ 'jxl-modular-write': modularWriteChunks,
19
22
  'jxl-groups': groupChunks,
20
23
  'jxl-post': postChunks,
21
24
  };
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = '3.13.2';
1
+ export const VERSION = '3.14.0';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "imagescript",
3
- "version": "3.13.2",
3
+ "version": "3.14.0",
4
4
  "description": "Pure TypeScript image processing that runs everywhere",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",