imagescript 3.8.1 → 3.9.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,11 @@ 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
12
  const fourCC = (s) => s.charCodeAt(0) | s.charCodeAt(1) << 8 | s.charCodeAt(2) << 16 | s.charCodeAt(3) << 24;
12
13
  const RIFF = fourCC('RIFF'), WEBP = fourCC('WEBP');
13
14
  const VP8 = fourCC('VP8 '), VP8L = fourCC('VP8L'), VP8X = fourCC('VP8X');
14
- const ALPH = fourCC('ALPH'), ANIM = fourCC('ANIM'), ANMF = fourCC('ANMF'), EXIF = fourCC('EXIF');
15
+ const ALPH = fourCC('ALPH'), ANIM = fourCC('ANIM'), ANMF = fourCC('ANMF'), EXIF = fourCC('EXIF'), ICCP = fourCC('ICCP');
15
16
  function chunks(data, start, end) {
16
17
  const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
17
18
  const out = [];
@@ -116,6 +117,7 @@ export function decode(data, maxPixels = MAX_PIXELS) {
116
117
  const list = container(data);
117
118
  if (!list.length)
118
119
  throw new Error('WebP: no image data');
120
+ const icc = list.find(c => c.type === ICCP)?.data;
119
121
  let orientation = 1;
120
122
  const exif = list.find(c => c.type === EXIF);
121
123
  if (exif)
@@ -123,7 +125,7 @@ export function decode(data, maxPixels = MAX_PIXELS) {
123
125
  if (list.some(c => c.type === ANMF)) {
124
126
  const animation = decodeAnimation(data, true, maxPixels);
125
127
  const frame = composite(animation)[0];
126
- return { width: animation.width, height: animation.height, pixels: frame.pixels, orientation };
128
+ return { width: animation.width, height: animation.height, pixels: frame.pixels, orientation, icc };
127
129
  }
128
130
  const image = decodeBitstream(list, maxPixels);
129
131
  if (list[0].type === VP8X && list[0].data.length >= 10) {
@@ -131,14 +133,14 @@ export function decode(data, maxPixels = MAX_PIXELS) {
131
133
  if (width !== image.width || height !== image.height)
132
134
  throw new Error('WebP: canvas and image sizes differ');
133
135
  }
134
- return { ...image, orientation };
136
+ return { ...image, orientation, icc };
135
137
  }
136
138
  export function decodeAnimation(data, onlyFirstFrame = false, maxPixels = MAX_PIXELS) {
137
139
  const list = container(data);
138
140
  const header = list[0];
139
141
  if (!header || header.type !== VP8X || !list.some(c => c.type === ANMF)) {
140
142
  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 }] };
143
+ 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
144
  }
143
145
  if (header.data.length < 10)
144
146
  throw new Error('WebP: invalid VP8X chunk');
@@ -173,7 +175,7 @@ export function decodeAnimation(data, onlyFirstFrame = false, maxPixels = MAX_PI
173
175
  }
174
176
  if (!frames.length)
175
177
  throw new Error('WebP: animation without frames');
176
- return { width, height, loopCount, background, frames };
178
+ return { width, height, loopCount, background, frames, icc: list.find(c => c.type === ICCP)?.data };
177
179
  }
178
180
  export function composite({ width, height, frames }) {
179
181
  const canvas = new Uint8Array(width * height * 4);
@@ -268,8 +270,20 @@ export function encode(rgba, width, height, exif) {
268
270
  set24(vp8x, 7, height - 1);
269
271
  return riff([riffChunk('VP8X', vp8x), bitstream, riffChunk('EXIF', exif)]);
270
272
  }
271
- export function encodeLossy(rgba, width, height, quality, exif, method = 4, sharp = false) {
272
- const { alpha, chunks } = lossyChunks(rgba, width, height, quality, method, sharp);
273
+ export function lossyOptions(quality, effort, sharp, alphaQuality) {
274
+ if (quality === undefined)
275
+ return undefined;
276
+ const q = finite(quality, 'quality'), a = finite(alphaQuality, 'alphaQuality');
277
+ if (q < 0 || q > 100)
278
+ throw new RangeError(`quality must be 0-100, not ${q}`);
279
+ if (a < 0 || a > 100)
280
+ throw new RangeError(`alphaQuality must be 0-100, not ${a}`);
281
+ if (!Number.isInteger(effort) || effort < 0 || effort > 6)
282
+ throw new RangeError(`effort must be an integer 0-6, not ${effort}`);
283
+ return { quality: q, method: effort, sharp, alphaQuality: Math.round(a) };
284
+ }
285
+ export function encodeLossy(rgba, width, height, lossy, exif) {
286
+ const { alpha, chunks } = lossyChunks(rgba, width, height, lossy);
273
287
  if (!alpha && !exif)
274
288
  return riff(chunks);
275
289
  const vp8x = new Uint8Array(10);
@@ -278,7 +292,7 @@ export function encodeLossy(rgba, width, height, quality, exif, method = 4, shar
278
292
  set24(vp8x, 7, height - 1);
279
293
  return riff([riffChunk('VP8X', vp8x), ...chunks, ...exif ? [riffChunk('EXIF', exif)] : []]);
280
294
  }
281
- function lossyChunks(rgba, width, height, quality, method, sharp = false) {
295
+ function lossyChunks(rgba, width, height, { quality, method, sharp, alphaQuality }) {
282
296
  if (width > 16383 || height > 16383)
283
297
  throw new RangeError('WebP: lossy images can be at most 16383 pixels wide and high');
284
298
  const picture = rgbaToYUV(rgba, width, height, sharp);
@@ -287,14 +301,14 @@ function lossyChunks(rgba, width, height, quality, method, sharp = false) {
287
301
  padded.set(frame);
288
302
  const chunks = [riffChunk('VP8 ', padded)];
289
303
  if (picture.a)
290
- chunks.unshift(riffChunk('ALPH', encodeAlpha(picture.a, width, height, method)));
304
+ chunks.unshift(riffChunk('ALPH', encodeAlpha(picture.a, width, height, method, alphaQuality)));
291
305
  return { alpha: !!picture.a, chunks };
292
306
  }
293
307
  export function lossyTolerance(quality) {
294
308
  const value = Math.sqrt(quality / 100);
295
309
  return Math.max(1, Math.round(31 * (1 - value) + value));
296
310
  }
297
- export function encodeAnimation(frames, width, height, plays, exif, quality, method = 4, sharp = false) {
311
+ export function encodeAnimation(frames, width, height, plays, exif, lossy) {
298
312
  if (!frames.length)
299
313
  throw new Error('WebP: an animation needs at least one frame');
300
314
  if (width > 1 << 24 || height > 1 << 24)
@@ -302,16 +316,16 @@ export function encodeAnimation(frames, width, height, plays, exif, quality, met
302
316
  let alpha = false;
303
317
  for (const [i, f] of frames.entries())
304
318
  alpha ||= needsAlpha(f, i === 0, width, height);
305
- return animationFile(frames.map(f => frameChunk(f, quality, method, sharp)), width, height, plays, alpha, exif);
319
+ return animationFile(frames.map(f => frameChunk(f, lossy)), width, height, plays, alpha, exif);
306
320
  }
307
321
  export function needsAlpha(f, first, width, height) {
308
322
  return (first && (f.x > 0 || f.y > 0 || f.width < width || f.height < height)) || f.dispose || hasAlpha(f.pixels);
309
323
  }
310
- export function frameChunk(f, quality, method = 4, sharp = false) {
324
+ export function frameChunk(f, lossy) {
311
325
  if (f.x & 1 || f.y & 1)
312
326
  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);
327
+ const bitstream = !lossy ? riffChunk('VP8L', vp8l.encode(toARGB(f.pixels, f.width * f.height), f.width, f.height))
328
+ : concat(lossyChunks(f.pixels, f.width, f.height, lossy).chunks);
315
329
  const header = new Uint8Array(16);
316
330
  set24(header, 0, f.x >> 1);
317
331
  set24(header, 3, f.y >> 1);
package/dist/image.d.ts CHANGED
@@ -86,6 +86,12 @@ 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;
89
95
  /** Metadata to include, see {@link Metadata} */
90
96
  metadata?: Metadata;
91
97
  }
@@ -113,6 +119,15 @@ export interface SVGOptions {
113
119
  * Default: {@link Image.SVG_MODE_SCALE}
114
120
  */
115
121
  mode?: SVGScaleMode;
122
+ /**
123
+ * Fonts for `<text>` (TrueType, OpenType): each text gets the face its `font-family`, `font-weight`, `font-style`
124
+ * and `font-stretch` match best among them, by the names, weights and styles in the fonts (like browsers match
125
+ * installed fonts). Generic families (`serif`, `sans-serif`, `monospace`, ...) are the first font that fits them,
126
+ * other families and text without one get the first font's family; characters a face doesn't have come from the
127
+ * other fonts. Fonts the SVG embeds with `@font-face` (in data: URIs, also WOFF) are used too, before these for
128
+ * their family names. Without any fonts text isn't rendered. Default: `[]`
129
+ */
130
+ fonts?: BinaryData[];
116
131
  }
117
132
  /** Options of {@link Image.renderText}: the text color and layout, and its style (see {@link TextStyle}) */
118
133
  export interface TextOptions extends TextStyle {
@@ -125,6 +140,14 @@ export interface TextOptions extends TextStyle {
125
140
  export interface DecodeOptions {
126
141
  /** Whether to rotate/mirror JPEGs, TIFFs, PNGs and WebPs as their orientation tag (Exif or XMP) says. Default: `true` */
127
142
  applyOrientation?: boolean;
143
+ /**
144
+ * Whether to convert the colors of images with an embedded ICC profile (PNG, JPEG, WebP, AVIF, TIFF) to sRGB, like
145
+ * browsers show them: wide gamut photos (Display P3 from phones, Adobe RGB, ProPhoto) look as intended instead of
146
+ * washed out. Matrix/TRC profiles (RGB and gray) are applied, relative colorimetric (colors outside sRGB are
147
+ * clipped); profiles with only lookup tables, CMYK ones and ones that are sRGB anyway leave the pixels as they are.
148
+ * Default: `true`
149
+ */
150
+ applyColorProfile?: boolean;
128
151
  /**
129
152
  * The most pixels to decode: larger images throw a RangeError before anything that size is allocated, so small
130
153
  * files declaring huge images (decompression bombs) can't exhaust the memory. Default: `268402689` (16383², like
@@ -148,7 +171,8 @@ export interface JXLEncodeOptions {
148
171
  quality?: number;
149
172
  /**
150
173
  * 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`
174
+ * `cjxl -e 3`), 1 and 2 search their sizes like `cjxl -e 5` (2 tries more of the small ones), and 2 also stores
175
+ * text-like features that repeat (the glyphs of screenshots) once, as patches like `cjxl -e 7`. Default: `1`
152
176
  */
153
177
  effort?: number;
154
178
  /** Metadata to include, see {@link Metadata} */
@@ -790,7 +814,7 @@ export declare class Image {
790
814
  * quality
791
815
  * @param options See {@link WebPEncodeOptions}
792
816
  */
793
- encodeWebP({ quality, effort, sharpYuv, metadata }?: WebPEncodeOptions): Promise<Uint8Array>;
817
+ encodeWebP({ quality, effort, sharpYuv, alphaQuality, metadata }?: WebPEncodeOptions): Promise<Uint8Array>;
794
818
  /**
795
819
  * Encodes the image as run length encoded TGA (32 bit, or 24 bit if the image is opaque)
796
820
  * @param options See {@link EncodeOptions}
@@ -850,8 +874,8 @@ export declare class Image {
850
874
  /**
851
875
  * Creates a new image from the given SVG
852
876
  * 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
877
+ * masks, opacity, blend modes, filters (all primitives and the filter functions) and images embedded as data URIs
878
+ * (PNG, JPEG, GIF, WebP, SVG), and text with the given or embedded fonts (see {@link SVGOptions.fonts})
855
879
  * @param svg The SVG content
856
880
  * @param options See {@link SVGOptions}
857
881
  * @return The rendered SVG graphic
package/dist/image.js CHANGED
@@ -16,6 +16,7 @@ import * as quantize from "./codecs/quantize.js";
16
16
  import * as textRenderer from "./render/text.js";
17
17
  import * as svgRenderer from "./render/svg.js";
18
18
  import { view } from "./util/mem.js";
19
+ import { profileTransform } from "./util/icc.js";
19
20
  import { ImageType } from "./image-type.js";
20
21
  import { TextLayout } from "./text-layout.js";
21
22
  import { resolveMetadata, pngText, exifData } from "./metadata.js";
@@ -1025,16 +1026,12 @@ export class Image {
1025
1026
  const m = resolveMetadata(metadata);
1026
1027
  return jpeg.encode(this.__bytes__(), this.width, this.height, finite(quality, 'quality'), { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined });
1027
1028
  }
1028
- async encodeWebP({ quality, effort = 2, sharpYuv = false, metadata = {} } = {}) {
1029
+ async encodeWebP({ quality, effort = 2, sharpYuv = false, alphaQuality = 100, metadata = {} } = {}) {
1029
1030
  const exif = exifData(resolveMetadata(metadata));
1030
- if (quality === undefined)
1031
+ const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
1032
+ if (!lossy)
1031
1033
  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);
1034
+ return webp.encodeLossy(this.__bytes__(), this.width, this.height, lossy, exif);
1038
1035
  }
1039
1036
  async encodeTGA({ metadata = {} } = {}) {
1040
1037
  const { author, comment, creationTime: time, software } = resolveMetadata(metadata);
@@ -1066,7 +1063,7 @@ export class Image {
1066
1063
  return netpbm.encode(this.__bytes__(), this.width, this.height);
1067
1064
  }
1068
1065
  static async decode(input, options = {}) {
1069
- const { applyOrientation = true, maxPixels = MAX_PIXELS, toneMapping = 'reinhard' } = options;
1066
+ const { applyOrientation = true, applyColorProfile = true, maxPixels = MAX_PIXELS, toneMapping = 'reinhard' } = options;
1070
1067
  if (toneMapping !== 'reinhard' && toneMapping !== 'clamp')
1071
1068
  throw new TypeError(`toneMapping must be 'reinhard' or 'clamp', not ${String(toneMapping)}`);
1072
1069
  const data = view(input);
@@ -1107,6 +1104,8 @@ export class Image {
1107
1104
  return tga.decode(data, maxPixels);
1108
1105
  throw new Error('Unsupported image type');
1109
1106
  });
1107
+ if (applyColorProfile && decoded.icc)
1108
+ profileTransform(decoded.icc)?.(decoded.pixels);
1110
1109
  const image = new Image(decoded.width, decoded.height);
1111
1110
  image.bitmap = decoded.pixels;
1112
1111
  return applyOrientation && decoded.orientation ? image.__orient__(decoded.orientation) : image;
@@ -1167,7 +1166,7 @@ export class Image {
1167
1166
  return 3;
1168
1167
  }
1169
1168
  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 };
1169
+ const { size = 1, mode = Image.SVG_MODE_SCALE, fonts = [] } = isOptions(sizeOrOptions) ? sizeOrOptions : { size: sizeOrOptions, mode: modeArgument };
1171
1170
  if (![1, 2, 3].includes(mode))
1172
1171
  throw new Error('Invalid SVG scaling mode');
1173
1172
  if (mode === Image.SVG_MODE_SCALE && size <= 0)
@@ -1192,7 +1191,7 @@ export class Image {
1192
1191
  catch {
1193
1192
  }
1194
1193
  }
1195
- const { width, height, pixels } = svgRenderer.render(source, mode, size, images);
1194
+ const { width, height, pixels } = svgRenderer.render(source, mode, size, images, fonts.map(font => view(font)));
1196
1195
  const image = new Image(width, height);
1197
1196
  image.bitmap.set(pixels);
1198
1197
  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
  }