imagescript 3.8.1 → 3.10.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,10 +8,12 @@ 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";
12
+ import { startThreads } from "../util/threads.js";
11
13
  const fourCC = (s) => s.charCodeAt(0) | s.charCodeAt(1) << 8 | s.charCodeAt(2) << 16 | s.charCodeAt(3) << 24;
12
14
  const RIFF = fourCC('RIFF'), WEBP = fourCC('WEBP');
13
15
  const VP8 = fourCC('VP8 '), VP8L = fourCC('VP8L'), VP8X = fourCC('VP8X');
14
- const ALPH = fourCC('ALPH'), ANIM = fourCC('ANIM'), ANMF = fourCC('ANMF'), EXIF = fourCC('EXIF');
16
+ const ALPH = fourCC('ALPH'), ANIM = fourCC('ANIM'), ANMF = fourCC('ANMF'), EXIF = fourCC('EXIF'), ICCP = fourCC('ICCP');
15
17
  function chunks(data, start, end) {
16
18
  const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
17
19
  const out = [];
@@ -116,6 +118,7 @@ export function decode(data, maxPixels = MAX_PIXELS) {
116
118
  const list = container(data);
117
119
  if (!list.length)
118
120
  throw new Error('WebP: no image data');
121
+ const icc = list.find(c => c.type === ICCP)?.data;
119
122
  let orientation = 1;
120
123
  const exif = list.find(c => c.type === EXIF);
121
124
  if (exif)
@@ -123,7 +126,7 @@ export function decode(data, maxPixels = MAX_PIXELS) {
123
126
  if (list.some(c => c.type === ANMF)) {
124
127
  const animation = decodeAnimation(data, true, maxPixels);
125
128
  const frame = composite(animation)[0];
126
- return { width: animation.width, height: animation.height, pixels: frame.pixels, orientation };
129
+ return { width: animation.width, height: animation.height, pixels: frame.pixels, orientation, icc };
127
130
  }
128
131
  const image = decodeBitstream(list, maxPixels);
129
132
  if (list[0].type === VP8X && list[0].data.length >= 10) {
@@ -131,14 +134,14 @@ export function decode(data, maxPixels = MAX_PIXELS) {
131
134
  if (width !== image.width || height !== image.height)
132
135
  throw new Error('WebP: canvas and image sizes differ');
133
136
  }
134
- return { ...image, orientation };
137
+ return { ...image, orientation, icc };
135
138
  }
136
139
  export function decodeAnimation(data, onlyFirstFrame = false, maxPixels = MAX_PIXELS) {
137
140
  const list = container(data);
138
141
  const header = list[0];
139
142
  if (!header || header.type !== VP8X || !list.some(c => c.type === ANMF)) {
140
143
  const { width, height, pixels } = decodeBitstream(list, maxPixels);
141
- return { width, height, loopCount: 0, background: 0, frames: [{ x: 0, y: 0, width, height, duration: 0, blend: false, dispose: false, pixels }] };
144
+ return { width, height, loopCount: 0, background: 0, frames: [{ x: 0, y: 0, width, height, duration: 0, blend: false, dispose: false, pixels }], icc: list.find(c => c.type === ICCP)?.data };
142
145
  }
143
146
  if (header.data.length < 10)
144
147
  throw new Error('WebP: invalid VP8X chunk');
@@ -173,7 +176,7 @@ export function decodeAnimation(data, onlyFirstFrame = false, maxPixels = MAX_PI
173
176
  }
174
177
  if (!frames.length)
175
178
  throw new Error('WebP: animation without frames');
176
- return { width, height, loopCount, background, frames };
179
+ return { width, height, loopCount, background, frames, icc: list.find(c => c.type === ICCP)?.data };
177
180
  }
178
181
  export function composite({ width, height, frames }) {
179
182
  const canvas = new Uint8Array(width * height * 4);
@@ -258,8 +261,25 @@ const hasAlpha = (rgba) => {
258
261
  return true;
259
262
  return false;
260
263
  };
261
- export function encode(rgba, width, height, exif) {
262
- const bitstream = riffChunk('VP8L', vp8l.encode(toARGB(rgba, width * height), width, height));
264
+ const MIN_THREADED_PIXELS = 1536 << 10, PIXELS_PER_THREAD = 512 << 10;
265
+ export async function encode(rgba, width, height, exif, threads = 1) {
266
+ const n = Math.min(threads, Math.floor(width * height / PIXELS_PER_THREAD));
267
+ const pool = n > 1 && width * height >= MIN_THREADED_PIXELS ? startThreads(n) : null;
268
+ let stream;
269
+ try {
270
+ stream = await vp8l.encode(toARGB(rgba, width * height), width, height, pool);
271
+ }
272
+ catch (e) {
273
+ if (!pool)
274
+ throw e;
275
+ stream = await vp8l.encode(toARGB(rgba, width * height), width, height);
276
+ }
277
+ finally {
278
+ if (pool)
279
+ for (const t of pool)
280
+ t.terminate();
281
+ }
282
+ const bitstream = riffChunk('VP8L', stream);
263
283
  if (!exif)
264
284
  return riff([bitstream]);
265
285
  const vp8x = new Uint8Array(10);
@@ -268,8 +288,20 @@ export function encode(rgba, width, height, exif) {
268
288
  set24(vp8x, 7, height - 1);
269
289
  return riff([riffChunk('VP8X', vp8x), bitstream, riffChunk('EXIF', exif)]);
270
290
  }
271
- export function encodeLossy(rgba, width, height, quality, exif, method = 4, sharp = false) {
272
- const { alpha, chunks } = lossyChunks(rgba, width, height, quality, method, sharp);
291
+ export function lossyOptions(quality, effort, sharp, alphaQuality) {
292
+ if (quality === undefined)
293
+ 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}`);
301
+ return { quality: q, method: effort, sharp, alphaQuality: Math.round(a) };
302
+ }
303
+ export async function encodeLossy(rgba, width, height, lossy, exif) {
304
+ const { alpha, chunks } = await lossyChunks(rgba, width, height, lossy);
273
305
  if (!alpha && !exif)
274
306
  return riff(chunks);
275
307
  const vp8x = new Uint8Array(10);
@@ -278,7 +310,7 @@ export function encodeLossy(rgba, width, height, quality, exif, method = 4, shar
278
310
  set24(vp8x, 7, height - 1);
279
311
  return riff([riffChunk('VP8X', vp8x), ...chunks, ...exif ? [riffChunk('EXIF', exif)] : []]);
280
312
  }
281
- function lossyChunks(rgba, width, height, quality, method, sharp = false) {
313
+ async function lossyChunks(rgba, width, height, { quality, method, sharp, alphaQuality }) {
282
314
  if (width > 16383 || height > 16383)
283
315
  throw new RangeError('WebP: lossy images can be at most 16383 pixels wide and high');
284
316
  const picture = rgbaToYUV(rgba, width, height, sharp);
@@ -287,14 +319,14 @@ function lossyChunks(rgba, width, height, quality, method, sharp = false) {
287
319
  padded.set(frame);
288
320
  const chunks = [riffChunk('VP8 ', padded)];
289
321
  if (picture.a)
290
- chunks.unshift(riffChunk('ALPH', encodeAlpha(picture.a, width, height, method)));
322
+ chunks.unshift(riffChunk('ALPH', await encodeAlpha(picture.a, width, height, method, alphaQuality)));
291
323
  return { alpha: !!picture.a, chunks };
292
324
  }
293
325
  export function lossyTolerance(quality) {
294
326
  const value = Math.sqrt(quality / 100);
295
327
  return Math.max(1, Math.round(31 * (1 - value) + value));
296
328
  }
297
- export function encodeAnimation(frames, width, height, plays, exif, quality, method = 4, sharp = false) {
329
+ export async function encodeAnimation(frames, width, height, plays, exif, lossy) {
298
330
  if (!frames.length)
299
331
  throw new Error('WebP: an animation needs at least one frame');
300
332
  if (width > 1 << 24 || height > 1 << 24)
@@ -302,16 +334,19 @@ export function encodeAnimation(frames, width, height, plays, exif, quality, met
302
334
  let alpha = false;
303
335
  for (const [i, f] of frames.entries())
304
336
  alpha ||= needsAlpha(f, i === 0, width, height);
305
- return animationFile(frames.map(f => frameChunk(f, quality, method, sharp)), width, height, plays, alpha, exif);
337
+ const chunks = [];
338
+ for (const f of frames)
339
+ chunks.push(await frameChunk(f, lossy));
340
+ return animationFile(chunks, width, height, plays, alpha, exif);
306
341
  }
307
342
  export function needsAlpha(f, first, width, height) {
308
343
  return (first && (f.x > 0 || f.y > 0 || f.width < width || f.height < height)) || f.dispose || hasAlpha(f.pixels);
309
344
  }
310
- export function frameChunk(f, quality, method = 4, sharp = false) {
345
+ export async function frameChunk(f, lossy) {
311
346
  if (f.x & 1 || f.y & 1)
312
347
  throw new RangeError('WebP: frame offsets have to be even');
313
- const bitstream = quality === undefined ? riffChunk('VP8L', vp8l.encode(toARGB(f.pixels, f.width * f.height), f.width, f.height))
314
- : concat(lossyChunks(f.pixels, f.width, f.height, quality, method, sharp).chunks);
348
+ const bitstream = !lossy ? riffChunk('VP8L', await vp8l.encode(toARGB(f.pixels, f.width * f.height), f.width, f.height))
349
+ : concat((await lossyChunks(f.pixels, f.width, f.height, lossy)).chunks);
315
350
  const header = new Uint8Array(16);
316
351
  set24(header, 0, f.x >> 1);
317
352
  set24(header, 3, f.y >> 1);
package/dist/image.d.ts CHANGED
@@ -86,6 +86,19 @@ export interface WebPEncodeOptions {
86
86
  * hard color edges a lot larger (1200x800 red and blue squares: 2.7 times). Default: `false`
87
87
  */
88
88
  sharpYuv?: boolean;
89
+ /**
90
+ * For lossy compression, the alpha plane's quality (0-100, like cwebp's `-alpha_q`): below 100 its levels are
91
+ * reduced (to 2-16 up to 70, 16-256 above), which makes it compress better; the alpha plane is lossless otherwise.
92
+ * Default: `100`
93
+ */
94
+ alphaQuality?: number;
95
+ /**
96
+ * For lossless compression, at most this many worker threads search the predictors and prefix codes in parallel
97
+ * (the same file, faster), `1` for none. Images under about 1.5 megapixels, and runtimes whose workers can't share
98
+ * memory (browsers without cross-origin isolation), encode without them. Default: the processors available, at
99
+ * most 8
100
+ */
101
+ threads?: number;
89
102
  /** Metadata to include, see {@link Metadata} */
90
103
  metadata?: Metadata;
91
104
  }
@@ -113,6 +126,15 @@ export interface SVGOptions {
113
126
  * Default: {@link Image.SVG_MODE_SCALE}
114
127
  */
115
128
  mode?: SVGScaleMode;
129
+ /**
130
+ * Fonts for `<text>` (TrueType, OpenType): each text gets the face its `font-family`, `font-weight`, `font-style`
131
+ * and `font-stretch` match best among them, by the names, weights and styles in the fonts (like browsers match
132
+ * installed fonts). Generic families (`serif`, `sans-serif`, `monospace`, ...) are the first font that fits them,
133
+ * other families and text without one get the first font's family; characters a face doesn't have come from the
134
+ * other fonts. Fonts the SVG embeds with `@font-face` (in data: URIs, also WOFF) are used too, before these for
135
+ * their family names. Without any fonts text isn't rendered. Default: `[]`
136
+ */
137
+ fonts?: BinaryData[];
116
138
  }
117
139
  /** Options of {@link Image.renderText}: the text color and layout, and its style (see {@link TextStyle}) */
118
140
  export interface TextOptions extends TextStyle {
@@ -125,6 +147,14 @@ export interface TextOptions extends TextStyle {
125
147
  export interface DecodeOptions {
126
148
  /** Whether to rotate/mirror JPEGs, TIFFs, PNGs and WebPs as their orientation tag (Exif or XMP) says. Default: `true` */
127
149
  applyOrientation?: boolean;
150
+ /**
151
+ * Whether to convert the colors of images with an embedded ICC profile (PNG, JPEG, WebP, AVIF, TIFF) to sRGB, like
152
+ * browsers show them: wide gamut photos (Display P3 from phones, Adobe RGB, ProPhoto) look as intended instead of
153
+ * washed out. Matrix/TRC profiles (RGB and gray) are applied, relative colorimetric (colors outside sRGB are
154
+ * clipped); profiles with only lookup tables, CMYK ones and ones that are sRGB anyway leave the pixels as they are.
155
+ * Default: `true`
156
+ */
157
+ applyColorProfile?: boolean;
128
158
  /**
129
159
  * The most pixels to decode: larger images throw a RangeError before anything that size is allocated, so small
130
160
  * files declaring huge images (decompression bombs) can't exhaust the memory. Default: `268402689` (16383², like
@@ -138,6 +168,13 @@ export interface DecodeOptions {
138
168
  * brighter than white. Default: `'reinhard'`
139
169
  */
140
170
  toneMapping?: ToneMapping;
171
+ /**
172
+ * At most this many worker threads decode in parallel (lossy JPEG XLs from 4 megapixels on, one per 2 megapixels
173
+ * at most, lossless ones from 1.5 megapixels and 512 KiB on; AVIFs from 4 megapixels on: the conversion to RGB,
174
+ * one per megapixel, and the tiles of grids), `1` for none. Default: the processors available, at most 8 (1 where
175
+ * workers can't share memory)
176
+ */
177
+ threads?: number;
141
178
  }
142
179
  /** Options of {@link Image.encodeJXL} */
143
180
  export interface JXLEncodeOptions {
@@ -148,9 +185,18 @@ export interface JXLEncodeOptions {
148
185
  quality?: number;
149
186
  /**
150
187
  * How hard lossy compression searches for the best transforms: 0-2, faster to smaller. 0 uses 8x8 DCTs only (like
151
- * `cjxl -e 3`), 1 and 2 search their sizes like `cjxl -e 5` (2 tries more of the small ones). Default: `1`
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`
152
190
  */
153
191
  effort?: number;
192
+ /**
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.
197
+ * Default: the processors available, at most 8
198
+ */
199
+ threads?: number;
154
200
  /** Metadata to include, see {@link Metadata} */
155
201
  metadata?: Metadata;
156
202
  }
@@ -164,6 +210,13 @@ export interface AVIFEncodeOptions {
164
210
  subsampling?: '4:4:4' | '4:2:0';
165
211
  /** How hard the encoder searches for the best modes: 0-2, faster to smaller. Default: `1` */
166
212
  effort?: number;
213
+ /**
214
+ * At most this many worker threads encode in parallel (the same file, faster: 2.9 times with 8 on a 1920x1080
215
+ * photo at effort 1), `1` for none. Small images (under about 640x640 pixels at effort 0, 448x448 at 1, 320x320
216
+ * at 2), and runtimes whose workers can't share memory (browsers without cross-origin isolation), encode without
217
+ * them. Default: the processors available, at most 8
218
+ */
219
+ threads?: number;
167
220
  /** Metadata to include, see {@link Metadata} */
168
221
  metadata?: Metadata;
169
222
  }
@@ -790,7 +843,7 @@ export declare class Image {
790
843
  * quality
791
844
  * @param options See {@link WebPEncodeOptions}
792
845
  */
793
- encodeWebP({ quality, effort, sharpYuv, metadata }?: WebPEncodeOptions): Promise<Uint8Array>;
846
+ encodeWebP({ quality, effort, sharpYuv, alphaQuality, threads, metadata }?: WebPEncodeOptions): Promise<Uint8Array>;
794
847
  /**
795
848
  * Encodes the image as run length encoded TGA (32 bit, or 24 bit if the image is opaque)
796
849
  * @param options See {@link EncodeOptions}
@@ -809,7 +862,7 @@ export declare class Image {
809
862
  * Encodes the image as AVIF (AV1, with an alpha image if the image has transparency)
810
863
  * @param options See {@link AVIFEncodeOptions}
811
864
  */
812
- encodeAVIF({ quality, alphaQuality, subsampling, effort, metadata }?: AVIFEncodeOptions): Promise<Uint8Array>;
865
+ encodeAVIF({ quality, alphaQuality, subsampling, effort, threads, metadata }?: AVIFEncodeOptions): Promise<Uint8Array>;
813
866
  /**
814
867
  * Encodes the image as JPEG XL: losslessly (the default), the codestream byte for byte like libjxl's `cjxl -e 1` on
815
868
  * CPUs with AVX2 or NEON (its fast lossless mode: the gradient predictor, a palette if the image has at most 511
@@ -818,7 +871,7 @@ export declare class Image {
818
871
  * transparency) is lossless either way. The codestream is in the container, with the metadata as Exif
819
872
  * @param options See {@link JXLEncodeOptions}
820
873
  */
821
- encodeJXL({ quality, effort, metadata }?: JXLEncodeOptions): Promise<Uint8Array>;
874
+ encodeJXL({ quality, effort, threads, metadata }?: JXLEncodeOptions): Promise<Uint8Array>;
822
875
  /**
823
876
  * Encodes the image as the smallest fitting Netpbm format: PBM for black and white images, PGM for greyscale ones,
824
877
  * PPM for others, PAM if the image has transparency
@@ -850,8 +903,8 @@ export declare class Image {
850
903
  /**
851
904
  * Creates a new image from the given SVG
852
905
  * Supports shapes, paths, transforms, use/symbol, CSS styles, gradients, patterns, strokes, markers, clip paths,
853
- * masks, opacity, filters (all primitives and the filter functions) and images embedded as data URIs (PNG, JPEG,
854
- * GIF, WebP, SVG); text is not rendered
906
+ * masks, opacity, blend modes, filters (all primitives and the filter functions) and images embedded as data URIs
907
+ * (PNG, JPEG, GIF, WebP, SVG), and text with the given or embedded fonts (see {@link SVGOptions.fonts})
855
908
  * @param svg The SVG content
856
909
  * @param options See {@link SVGOptions}
857
910
  * @return The rendered SVG graphic
package/dist/image.js CHANGED
@@ -11,11 +11,18 @@ import * as netpbm from "./codecs/netpbm.js";
11
11
  import * as hdr from "./codecs/hdr.js";
12
12
  import * as avif from "./codecs/avif.js";
13
13
  import * as avifEnc from "./codecs/avif-enc.js";
14
+ import { availableThreads } from "./util/threads.js";
15
+ const defaultThreads = () => Math.max(1, Math.min(availableThreads(), 8));
16
+ const checkThreads = (threads) => {
17
+ if (!Number.isInteger(threads) || threads < 1)
18
+ throw new RangeError(`threads must be a positive integer, not ${threads}`);
19
+ };
14
20
  import * as jxl from "./codecs/jxl.js";
15
21
  import * as quantize from "./codecs/quantize.js";
16
22
  import * as textRenderer from "./render/text.js";
17
23
  import * as svgRenderer from "./render/svg.js";
18
24
  import { view } from "./util/mem.js";
25
+ import { profileTransform } from "./util/icc.js";
19
26
  import { ImageType } from "./image-type.js";
20
27
  import { TextLayout } from "./text-layout.js";
21
28
  import { resolveMetadata, pngText, exifData } from "./metadata.js";
@@ -1025,16 +1032,13 @@ export class Image {
1025
1032
  const m = resolveMetadata(metadata);
1026
1033
  return jpeg.encode(this.__bytes__(), this.width, this.height, finite(quality, 'quality'), { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined });
1027
1034
  }
1028
- async encodeWebP({ quality, effort = 2, sharpYuv = false, metadata = {} } = {}) {
1035
+ async encodeWebP({ quality, effort = 2, sharpYuv = false, alphaQuality = 100, threads = defaultThreads(), metadata = {} } = {}) {
1036
+ checkThreads(threads);
1029
1037
  const exif = exifData(resolveMetadata(metadata));
1030
- if (quality === undefined)
1031
- return webp.encode(this.__bytes__(), this.width, this.height, exif);
1032
- const q = finite(quality, 'quality');
1033
- if (q < 0 || q > 100)
1034
- throw new RangeError(`quality must be 0-100, not ${q}`);
1035
- if (!Number.isInteger(effort) || effort < 0 || effort > 6)
1036
- throw new RangeError(`effort must be an integer 0-6, not ${effort}`);
1037
- return webp.encodeLossy(this.__bytes__(), this.width, this.height, q, exif, effort, sharpYuv);
1038
+ const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
1039
+ if (!lossy)
1040
+ return webp.encode(this.__bytes__(), this.width, this.height, exif, threads);
1041
+ return webp.encodeLossy(this.__bytes__(), this.width, this.height, lossy, exif);
1038
1042
  }
1039
1043
  async encodeTGA({ metadata = {} } = {}) {
1040
1044
  const { author, comment, creationTime: time, software } = resolveMetadata(metadata);
@@ -1046,13 +1050,15 @@ export class Image {
1046
1050
  async encodeQOI() {
1047
1051
  return qoi.encode(this.__bytes__(), this.width, this.height);
1048
1052
  }
1049
- async encodeAVIF({ quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1, metadata = {} } = {}) {
1053
+ async encodeAVIF({ quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1, threads = defaultThreads(), metadata = {} } = {}) {
1054
+ checkThreads(threads);
1050
1055
  const exif = exifData(resolveMetadata(metadata));
1051
- return avifEnc.encode(this.__bytes__(), this.width, this.height, { quality: finite(quality, 'quality'), alphaQuality: finite(alphaQuality, 'alphaQuality'), subsampling, effort, exif });
1056
+ return avifEnc.encode(this.__bytes__(), this.width, this.height, { quality: finite(quality, 'quality'), alphaQuality: finite(alphaQuality, 'alphaQuality'), subsampling, effort, exif, threads });
1052
1057
  }
1053
- async encodeJXL({ quality, effort = 1, metadata = {} } = {}) {
1058
+ async encodeJXL({ quality, effort = 1, threads = defaultThreads(), metadata = {} } = {}) {
1054
1059
  if (!Number.isInteger(effort) || effort < 0 || effort > 2)
1055
1060
  throw new RangeError(`effort must be an integer 0-2, not ${effort}`);
1061
+ checkThreads(threads);
1056
1062
  let distance = 0;
1057
1063
  if (quality !== undefined) {
1058
1064
  const q = finite(quality, 'quality');
@@ -1060,13 +1066,14 @@ export class Image {
1060
1066
  throw new RangeError(`quality must be 0-100, not ${q}`);
1061
1067
  distance = q >= 100 ? 0 : q >= 30 ? 0.1 + (100 - q) * 0.09 : 53 / 3000 * q * q - 23 / 20 * q + 25;
1062
1068
  }
1063
- return jxl.encode(this.__bytes__(), this.width, this.height, exifData(resolveMetadata(metadata)), distance, effort);
1069
+ return jxl.encode(this.__bytes__(), this.width, this.height, exifData(resolveMetadata(metadata)), distance, effort, threads);
1064
1070
  }
1065
1071
  async encodePNM() {
1066
1072
  return netpbm.encode(this.__bytes__(), this.width, this.height);
1067
1073
  }
1068
1074
  static async decode(input, options = {}) {
1069
- const { applyOrientation = true, maxPixels = MAX_PIXELS, toneMapping = 'reinhard' } = options;
1075
+ const { applyOrientation = true, applyColorProfile = true, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = defaultThreads() } = options;
1076
+ checkThreads(threads);
1070
1077
  if (toneMapping !== 'reinhard' && toneMapping !== 'clamp')
1071
1078
  throw new TypeError(`toneMapping must be 'reinhard' or 'clamp', not ${String(toneMapping)}`);
1072
1079
  const data = view(input);
@@ -1090,9 +1097,9 @@ export class Image {
1090
1097
  return { width, height, pixels };
1091
1098
  };
1092
1099
  if (ImageType.isAVIF(dataView))
1093
- return avif.decode(data, maxPixels, toneMapping);
1100
+ return avif.decode(data, maxPixels, toneMapping, threads);
1094
1101
  if (ImageType.isJXL(dataView))
1095
- return jxl.decode(data, maxPixels, toneMapping);
1102
+ return jxl.decode(data, maxPixels, toneMapping, threads);
1096
1103
  if (ImageType.isBMP(dataView))
1097
1104
  return bitmap(bmp.decode(data, maxPixels));
1098
1105
  if (ImageType.isICO(dataView))
@@ -1107,6 +1114,8 @@ export class Image {
1107
1114
  return tga.decode(data, maxPixels);
1108
1115
  throw new Error('Unsupported image type');
1109
1116
  });
1117
+ if (applyColorProfile && decoded.icc)
1118
+ profileTransform(decoded.icc)?.(decoded.pixels);
1110
1119
  const image = new Image(decoded.width, decoded.height);
1111
1120
  image.bitmap = decoded.pixels;
1112
1121
  return applyOrientation && decoded.orientation ? image.__orient__(decoded.orientation) : image;
@@ -1167,7 +1176,7 @@ export class Image {
1167
1176
  return 3;
1168
1177
  }
1169
1178
  static async renderSVG(svg, sizeOrOptions = 1, modeArgument = Image.SVG_MODE_SCALE) {
1170
- const { size = 1, mode = Image.SVG_MODE_SCALE } = isOptions(sizeOrOptions) ? sizeOrOptions : { size: sizeOrOptions, mode: modeArgument };
1179
+ const { size = 1, mode = Image.SVG_MODE_SCALE, fonts = [] } = isOptions(sizeOrOptions) ? sizeOrOptions : { size: sizeOrOptions, mode: modeArgument };
1171
1180
  if (![1, 2, 3].includes(mode))
1172
1181
  throw new Error('Invalid SVG scaling mode');
1173
1182
  if (mode === Image.SVG_MODE_SCALE && size <= 0)
@@ -1192,7 +1201,7 @@ export class Image {
1192
1201
  catch {
1193
1202
  }
1194
1203
  }
1195
- const { width, height, pixels } = svgRenderer.render(source, mode, size, images);
1204
+ const { width, height, pixels } = svgRenderer.render(source, mode, size, images, fonts.map(font => view(font)));
1196
1205
  const image = new Image(width, height);
1197
1206
  image.bitmap.set(pixels);
1198
1207
  return image;
@@ -0,0 +1,102 @@
1
+ /*!
2
+ * Blend modes on premultiplied colors, ported from tiny-skia (https://github.com/linebender/tiny-skia,
3
+ * src/pipeline/highp.rs; Copyright 2011 Google Inc., 2020 Yevhenii Reizner, BSD-3-Clause License, itself from Skia).
4
+ * See THIRD_PARTY_NOTICES.md
5
+ */
6
+ export const BLEND_MODES = new Set(['normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light',
7
+ 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity', 'plus-lighter']);
8
+ const inv = (v) => 1 - v;
9
+ const lum = (r, g, b) => r * 0.3 + g * 0.59 + b * 0.11;
10
+ const sat = (r, g, b) => Math.max(r, g, b) - Math.min(r, g, b);
11
+ function setSat(c, value) {
12
+ const mn = Math.min(c[0], c[1], c[2]), mx = Math.max(c[0], c[1], c[2]), range = mx - mn;
13
+ for (let k = 0; k < 3; k++)
14
+ c[k] = range === 0 ? 0 : (c[k] - mn) * value / range;
15
+ }
16
+ function setLum(c, l) {
17
+ const diff = l - lum(c[0], c[1], c[2]);
18
+ for (let k = 0; k < 3; k++)
19
+ c[k] += diff;
20
+ }
21
+ function clipColor(c, a) {
22
+ const mn = Math.min(c[0], c[1], c[2]), mx = Math.max(c[0], c[1], c[2]), l = lum(c[0], c[1], c[2]);
23
+ for (let k = 0; k < 3; k++) {
24
+ let v = c[k];
25
+ if (!(mx >= 0))
26
+ v = l + (v - l) * l / (l - mn);
27
+ if (mx > a)
28
+ v = l + (v - l) * (a - l) / (mx - l);
29
+ c[k] = Math.max(v, 0);
30
+ }
31
+ }
32
+ function separable(mode, sc, dc, sa, da) {
33
+ switch (mode) {
34
+ case 'multiply': return sc * inv(da) + dc * inv(sa) + sc * dc;
35
+ case 'screen': return sc + dc - sc * dc;
36
+ case 'darken': return sc + dc - Math.max(sc * da, dc * sa);
37
+ case 'lighten': return sc + dc - Math.min(sc * da, dc * sa);
38
+ case 'difference': return sc + dc - 2 * Math.min(sc * da, dc * sa);
39
+ case 'exclusion': return sc + dc - 2 * sc * dc;
40
+ case 'color-burn':
41
+ return dc === da ? dc + sc * inv(da) : sc === 0 ? dc * inv(sa) : sa * (da - Math.min(da, (da - dc) * sa / sc)) + sc * inv(da) + dc * inv(sa);
42
+ case 'color-dodge':
43
+ return dc === 0 ? sc * inv(da) : sc === sa ? sc + dc * inv(sa) : sa * Math.min(da, dc * sa / (sa - sc)) + sc * inv(da) + dc * inv(sa);
44
+ case 'hard-light':
45
+ return sc * inv(da) + dc * inv(sa) + (2 * sc <= sa ? 2 * sc * dc : sa * da - 2 * (da - dc) * (sa - sc));
46
+ case 'overlay':
47
+ return sc * inv(da) + dc * inv(sa) + (2 * dc <= da ? 2 * sc * dc : sa * da - 2 * (da - dc) * (sa - sc));
48
+ case 'soft-light': {
49
+ const m = da > 0 ? dc / da : 0, s2 = 2 * sc, m4 = 4 * m;
50
+ const darkSrc = dc * (sa + (s2 - sa) * (1 - m));
51
+ const darkDst = (m4 * m4 + m4) * (m - 1) + 7 * m;
52
+ const liteDst = Math.sqrt(m) - m;
53
+ const liteSrc = dc * sa + da * (s2 - sa) * (4 * dc <= da ? darkDst : liteDst);
54
+ return sc * inv(da) + dc * inv(sa) + (s2 <= sa ? darkSrc : liteSrc);
55
+ }
56
+ case 'plus-lighter': return Math.min(sc + dc, 1);
57
+ default: return sc + dc * inv(sa);
58
+ }
59
+ }
60
+ const c = [0, 0, 0];
61
+ export function blendPixel(mode, r, g, b, a, d, i) {
62
+ const dr = d[i], dg = d[i + 1], db = d[i + 2], da = d[i + 3];
63
+ if (mode === 'hue' || mode === 'saturation' || mode === 'color' || mode === 'luminosity') {
64
+ if (mode === 'hue') {
65
+ c[0] = r * a;
66
+ c[1] = g * a;
67
+ c[2] = b * a;
68
+ setSat(c, sat(dr, dg, db) * a);
69
+ setLum(c, lum(dr, dg, db) * a);
70
+ }
71
+ else if (mode === 'saturation') {
72
+ c[0] = dr * a;
73
+ c[1] = dg * a;
74
+ c[2] = db * a;
75
+ setSat(c, sat(r, g, b) * da);
76
+ setLum(c, lum(dr, dg, db) * a);
77
+ }
78
+ else if (mode === 'color') {
79
+ c[0] = r * da;
80
+ c[1] = g * da;
81
+ c[2] = b * da;
82
+ setLum(c, lum(dr, dg, db) * a);
83
+ }
84
+ else {
85
+ c[0] = dr * a;
86
+ c[1] = dg * a;
87
+ c[2] = db * a;
88
+ setLum(c, lum(r, g, b) * da);
89
+ }
90
+ clipColor(c, a * da);
91
+ d[i] = r * inv(da) + dr * inv(a) + c[0];
92
+ d[i + 1] = g * inv(da) + dg * inv(a) + c[1];
93
+ d[i + 2] = b * inv(da) + db * inv(a) + c[2];
94
+ d[i + 3] = a + da - a * da;
95
+ }
96
+ else {
97
+ d[i] = separable(mode, r, dr, a, da);
98
+ d[i + 1] = separable(mode, g, dg, a, da);
99
+ d[i + 2] = separable(mode, b, db, a, da);
100
+ d[i + 3] = mode === 'plus-lighter' ? Math.min(a + da, 1) : da * inv(a) + a;
101
+ }
102
+ }
@@ -3,12 +3,11 @@
3
3
  * crates/resvg/src/filter: mod.rs, box_blur.rs (itself based on https://github.com/fschutt/fastblur), iir_blur.rs,
4
4
  * color_matrix.rs, component_transfer.rs, composite.rs, morphology.rs, convolve_matrix.rs, turbulence.rs (itself from
5
5
  * the reference implementation in the SVG 1.1 specification), lighting.rs, displacement_map.rs; Copyright 2017 the Resvg
6
- * Authors, MIT License) and the blend modes of tiny-skia (https://github.com/linebender/tiny-skia,
7
- * src/pipeline/highp.rs; Copyright 2011 Google Inc., 2020 Yevhenii Reizner, BSD-3-Clause License,
8
- * itself from Skia). The IIR blur
6
+ * Authors, MIT License). The IIR blur
9
7
  * follows Pascal Getreuer's gaussianiir (http://www.getreuer.info/home/gaussianiir; Simplified BSD License), an
10
8
  * implementation of Alvarez and Mazorra's fast Gaussian convolution. See THIRD_PARTY_NOTICES.md
11
9
  */
10
+ import { blendPixel } from "./blend.js";
12
11
  const TO_LINEAR = new Uint8Array(256), TO_SRGB = new Uint8Array(256);
13
12
  for (let i = 0; i < 256; i++) {
14
13
  const c = i / 255;
@@ -572,94 +571,11 @@ function transfer(f, value) {
572
571
  }
573
572
  function blend(dst, src, mode) {
574
573
  const s = src.data, d = dst.data;
575
- const inv = (v) => 1 - v;
576
- const lum = (r, g, b) => r * 0.3 + g * 0.59 + b * 0.11;
577
- const sat = (r, g, b) => Math.max(r, g, b) - Math.min(r, g, b);
578
- const setSat = (c, value) => {
579
- const mn = Math.min(c[0], c[1], c[2]), mx = Math.max(c[0], c[1], c[2]), range = mx - mn;
580
- for (let k = 0; k < 3; k++)
581
- c[k] = range === 0 ? 0 : (c[k] - mn) * value / range;
582
- };
583
- const setLum = (c, l) => {
584
- const diff = l - lum(c[0], c[1], c[2]);
585
- for (let k = 0; k < 3; k++)
586
- c[k] += diff;
587
- };
588
- const clipColor = (c, a) => {
589
- const mn = Math.min(c[0], c[1], c[2]), mx = Math.max(c[0], c[1], c[2]), l = lum(c[0], c[1], c[2]);
590
- for (let k = 0; k < 3; k++) {
591
- let v = c[k];
592
- if (!(mx >= 0))
593
- v = l + (v - l) * l / (l - mn);
594
- if (mx > a)
595
- v = l + (v - l) * (a - l) / (mx - l);
596
- c[k] = Math.max(v, 0);
597
- }
598
- };
599
- const separable = (sc, dc, sa, da) => {
600
- switch (mode) {
601
- case 'multiply': return sc * inv(da) + dc * inv(sa) + sc * dc;
602
- case 'screen': return sc + dc - sc * dc;
603
- case 'darken': return sc + dc - Math.max(sc * da, dc * sa);
604
- case 'lighten': return sc + dc - Math.min(sc * da, dc * sa);
605
- case 'difference': return sc + dc - 2 * Math.min(sc * da, dc * sa);
606
- case 'exclusion': return sc + dc - 2 * sc * dc;
607
- case 'color-burn':
608
- return dc === da ? dc + sc * inv(da) : sc === 0 ? dc * inv(sa) : sa * (da - Math.min(da, (da - dc) * sa / sc)) + sc * inv(da) + dc * inv(sa);
609
- case 'color-dodge':
610
- return dc === 0 ? sc * inv(da) : sc === sa ? sc + dc * inv(sa) : sa * Math.min(da, dc * sa / (sa - sc)) + sc * inv(da) + dc * inv(sa);
611
- case 'hard-light':
612
- return sc * inv(da) + dc * inv(sa) + (2 * sc <= sa ? 2 * sc * dc : sa * da - 2 * (da - dc) * (sa - sc));
613
- case 'overlay':
614
- return sc * inv(da) + dc * inv(sa) + (2 * dc <= da ? 2 * sc * dc : sa * da - 2 * (da - dc) * (sa - sc));
615
- case 'soft-light': {
616
- const m = da > 0 ? dc / da : 0, s2 = 2 * sc, m4 = 4 * m;
617
- const darkSrc = dc * (sa + (s2 - sa) * (1 - m));
618
- const darkDst = (m4 * m4 + m4) * (m - 1) + 7 * m;
619
- const liteDst = Math.sqrt(m) - m;
620
- const liteSrc = dc * sa + da * (s2 - sa) * (4 * dc <= da ? darkDst : liteDst);
621
- return sc * inv(da) + dc * inv(sa) + (s2 <= sa ? darkSrc : liteSrc);
622
- }
623
- default: return sc + dc * inv(sa);
624
- }
625
- };
626
- const c = [0, 0, 0];
574
+ const out = [0, 0, 0, 0];
627
575
  for (let i = 0; i < d.length; i += 4) {
628
- const r = s[i] / 255, g = s[i + 1] / 255, b = s[i + 2] / 255, a = s[i + 3] / 255;
629
- const dr = d[i] / 255, dg = d[i + 1] / 255, db = d[i + 2] / 255, da = d[i + 3] / 255;
630
- let out;
631
- if (mode === 'hue' || mode === 'saturation' || mode === 'color' || mode === 'luminosity') {
632
- if (mode === 'hue') {
633
- c[0] = r * a;
634
- c[1] = g * a;
635
- c[2] = b * a;
636
- setSat(c, sat(dr, dg, db) * a);
637
- setLum(c, lum(dr, dg, db) * a);
638
- }
639
- else if (mode === 'saturation') {
640
- c[0] = dr * a;
641
- c[1] = dg * a;
642
- c[2] = db * a;
643
- setSat(c, sat(r, g, b) * da);
644
- setLum(c, lum(dr, dg, db) * a);
645
- }
646
- else if (mode === 'color') {
647
- c[0] = r * da;
648
- c[1] = g * da;
649
- c[2] = b * da;
650
- setLum(c, lum(dr, dg, db) * a);
651
- }
652
- else {
653
- c[0] = dr * a;
654
- c[1] = dg * a;
655
- c[2] = db * a;
656
- setLum(c, lum(r, g, b) * da);
657
- }
658
- clipColor(c, a * da);
659
- out = [r * inv(da) + dr * inv(a) + c[0], g * inv(da) + dg * inv(a) + c[1], b * inv(da) + db * inv(a) + c[2], a + da - a * da];
660
- }
661
- else
662
- out = [separable(r, dr, a, da), separable(g, dg, a, da), separable(b, db, a, da), da * inv(a) + a];
576
+ for (let k = 0; k < 4; k++)
577
+ out[k] = d[i + k] / 255;
578
+ blendPixel(mode, s[i] / 255, s[i + 1] / 255, s[i + 2] / 255, s[i + 3] / 255, out, 0);
663
579
  for (let k = 0; k < 4; k++)
664
580
  d[i + k] = u8(clamp(0, out[k], 1) * 255 + 0.5);
665
581
  }