imagescript 3.19.0 → 3.20.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.
@@ -62,13 +62,94 @@ function exactPalette(pixels, limit) {
62
62
  palette.push(0, 0, 0);
63
63
  return { palette: Uint8Array.from(palette), indices };
64
64
  }
65
- function medianCut(pixels, colors, iterations, include) {
65
+ export function buildPalette(pixels, colors, minAlpha) {
66
+ const seen = new Set();
67
+ let exact = true;
68
+ for (let i = 0; i < pixels.length && exact; i += 4) {
69
+ if (pixels[i + 3] < minAlpha)
70
+ continue;
71
+ const key = pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2];
72
+ if (seen.has(key))
73
+ continue;
74
+ if (seen.size === colors)
75
+ exact = false;
76
+ else
77
+ seen.add(key);
78
+ }
79
+ if (exact) {
80
+ const palette = new Uint8Array(seen.size * 3);
81
+ let p = 0;
82
+ for (const key of seen) {
83
+ palette[p++] = key >> 16;
84
+ palette[p++] = key >> 8 & 255;
85
+ palette[p++] = key & 255;
86
+ }
87
+ return palette;
88
+ }
89
+ return Uint8Array.from(medianCut(pixels, colors, 4, undefined, minAlpha).palette, Math.round);
90
+ }
91
+ const BAYER = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];
92
+ const FLOYD_STEINBERG = [[1, 0, 7 / 16], [-1, 1, 3 / 16], [0, 1, 5 / 16], [1, 1, 1 / 16]];
93
+ const ATKINSON = [[1, 0, 1 / 8], [2, 0, 1 / 8], [-1, 1, 1 / 8], [0, 1, 1 / 8], [1, 1, 1 / 8], [0, 2, 1 / 8]];
94
+ export function applyPalette(pixels, width, height, palette, dither, strength) {
95
+ const entries = palette.length / 3;
96
+ if (!entries)
97
+ return;
98
+ const nearest = nearestSearch(palette, entries);
99
+ const clampFloat = (v) => v < 0 ? 0 : v > 255 ? 255 : v;
100
+ if (dither === 'none' || dither === 'ordered') {
101
+ const spread = dither === 'ordered' ? strength * 255 / Math.cbrt(entries) : 0;
102
+ for (let y = 0, p = 0; y < height; y++) {
103
+ for (let x = 0; x < width; x++, p++) {
104
+ if (!pixels[p * 4 + 3])
105
+ continue;
106
+ const offset = spread ? ((BAYER[(y & 3) * 4 + (x & 3)] + 0.5) / 16 - 0.5) * spread : 0;
107
+ const index = nearest(clampFloat(pixels[p * 4] + offset), clampFloat(pixels[p * 4 + 1] + offset), clampFloat(pixels[p * 4 + 2] + offset));
108
+ pixels[p * 4] = palette[index * 3];
109
+ pixels[p * 4 + 1] = palette[index * 3 + 1];
110
+ pixels[p * 4 + 2] = palette[index * 3 + 2];
111
+ }
112
+ }
113
+ return;
114
+ }
115
+ const pattern = dither === 'atkinson' ? ATKINSON : FLOYD_STEINBERG;
116
+ const rows = [new Float32Array(width * 3), new Float32Array(width * 3), new Float32Array(width * 3)];
117
+ for (let y = 0; y < height; y++) {
118
+ const direction = y & 1 ? -1 : 1;
119
+ const current = rows[y % 3];
120
+ for (let step = 0; step < width; step++) {
121
+ const x = direction === 1 ? step : width - 1 - step;
122
+ const p = y * width + x;
123
+ if (!pixels[p * 4 + 3])
124
+ continue;
125
+ const e = x * 3;
126
+ const r = clampFloat(pixels[p * 4] + current[e]);
127
+ const g = clampFloat(pixels[p * 4 + 1] + current[e + 1]);
128
+ const b = clampFloat(pixels[p * 4 + 2] + current[e + 2]);
129
+ const index = nearest(r, g, b);
130
+ const errors = [r - palette[index * 3], g - palette[index * 3 + 1], b - palette[index * 3 + 2]];
131
+ pixels[p * 4] = palette[index * 3];
132
+ pixels[p * 4 + 1] = palette[index * 3 + 1];
133
+ pixels[p * 4 + 2] = palette[index * 3 + 2];
134
+ for (const [dx, dy, weight] of pattern) {
135
+ const tx = x + dx * direction, ty = y + dy;
136
+ if (tx < 0 || tx >= width || ty >= height)
137
+ continue;
138
+ const target = rows[ty % 3], t = tx * 3;
139
+ for (let c = 0; c < 3; c++)
140
+ target[t + c] += errors[c] * weight * strength;
141
+ }
142
+ }
143
+ current.fill(0);
144
+ }
145
+ }
146
+ function medianCut(pixels, colors, iterations, include, minAlpha = 128) {
66
147
  const count = new Float64Array(32768);
67
148
  const sumR = new Float64Array(32768);
68
149
  const sumG = new Float64Array(32768);
69
150
  const sumB = new Float64Array(32768);
70
151
  for (let i = 0; i < pixels.length; i += 4) {
71
- if (pixels[i + 3] < 128)
152
+ if (pixels[i + 3] < minAlpha)
72
153
  continue;
73
154
  const r = pixels[i], g = pixels[i + 1], b = pixels[i + 2];
74
155
  if (include && !include(r, g, b))
package/dist/image.d.ts CHANGED
@@ -113,6 +113,61 @@ export interface SharpenOptions {
113
113
  /** The radius of the blur the image is compared with (larger values sharpen coarser details). Default: `1` */
114
114
  radius?: number;
115
115
  }
116
+ /** Options of {@link Image.quantize}: either `colors` or `palette`, and the dithering */
117
+ export interface QuantizeOptions {
118
+ /**
119
+ * The number of colors to reduce the image to, an integer from 2 to 256. The palette is the image's own colors when
120
+ * it has no more distinct ones than this, else colors chosen by median cut (the common colors get their own). Those
121
+ * are averages of groups of similar colors, so e.g. pure black and white are only in it if the image has them in
122
+ * quantity: give `palette` for exact colors. Default: `256`. Give `colors` or `palette`, not both
123
+ */
124
+ colors?: number;
125
+ /**
126
+ * A fixed palette (1 to 256 colors, e.g. a Game Boy's four greens) that every pixel is mapped to, the nearest color
127
+ * by its RGB. The alpha of the palette's colors is ignored. Give `palette` or `colors`, not both
128
+ */
129
+ palette?: Color[];
130
+ /**
131
+ * How the rounding error of each pixel is handled, which makes gradients look smooth with few colors:
132
+ * `'none'` (each pixel takes its nearest color), `'floyd-steinberg'` (the error goes to the next pixels, 7/16, 3/16,
133
+ * 5/16 and 1/16), `'atkinson'` (the error goes to six neighbours, 1/8 each: lighter, more contrast), `'ordered'` (a
134
+ * regular 4x4 pattern of thresholds, no error spreading). Rows alternate direction for the error diffusions.
135
+ * Default: `'none'`
136
+ */
137
+ dither?: 'none' | 'floyd-steinberg' | 'atkinson' | 'ordered';
138
+ /**
139
+ * How strongly to dither, from `0` (no spreading or threshold, the same as `'none'`) to `1` (the full error or
140
+ * threshold). Default: `1`
141
+ */
142
+ ditherStrength?: number;
143
+ }
144
+ /** How {@link Image.transform} samples the pixels between the source's */
145
+ export type TransformMode = 'nearest-neighbor' | 'bilinear' | 'bicubic';
146
+ /** Options of {@link Image.transform} */
147
+ export interface TransformOptions {
148
+ /**
149
+ * The point the transform is applied around, in pixels: a rotation turns around it, a scale grows from it.
150
+ * Default: the middle of the image. It only decides where the result lies on a canvas that stays as large as the
151
+ * image (`expand: false`)
152
+ */
153
+ origin?: {
154
+ /** The x position of the point in pixels. Default: half the width */
155
+ x?: number;
156
+ /** The y position of the point in pixels. Default: half the height */
157
+ y?: number;
158
+ };
159
+ /**
160
+ * Whether to make the image as large as the transformed one, which then fills it (a rotated image grows to fit its
161
+ * corners, a skewed one gets wider). Without it, the image keeps its size and the parts outside are lost. Frames
162
+ * only grow up and left as far as their offset allows. Default: `true`
163
+ */
164
+ expand?: boolean;
165
+ /**
166
+ * How the pixels between the source's are sampled: `'nearest-neighbor'` (hard pixels, no smoothing, for pixel art),
167
+ * `'bilinear'` (smooth), `'bicubic'` (sharper, slower, can overshoot a little at hard edges). Default: `'bilinear'`
168
+ */
169
+ mode?: TransformMode;
170
+ }
116
171
  /** Options of {@link Image.dropShadow} */
117
172
  export interface ShadowOptions {
118
173
  /** How far to move the shadow to the right (negative values: to the left), in pixels. Default: `0` */
@@ -266,6 +321,14 @@ export interface SVGOptions {
266
321
  * before these for their family names. Without any fonts text isn't rendered. Default: `[]`
267
322
  */
268
323
  fonts?: BinaryData[];
324
+ /**
325
+ * Images for the `<image>` elements (and `feImage`) by their `href`, the same string the SVG uses: with
326
+ * `images: { 'logo.png': bytes }`, `<image href="logo.png" .../>` draws the image. Values are encoded images (PNG,
327
+ * JPEG, WebP, GIF's first frame, ...) or {@link Image}s, decoded like data URI images are, and only for the hrefs
328
+ * the SVG references. Nothing else is read: no files and no URLs, so an href that isn't given (and isn't a data URI)
329
+ * draws nothing. SVG documents can't be given this way, use a data URI for them. Default: `{}`
330
+ */
331
+ images?: Record<string, BinaryData | Image>;
269
332
  }
270
333
  /** Options of {@link Image.renderText}: the text color and layout, and its style (see {@link TextStyle}) */
271
334
  export interface TextOptions extends TextStyle {
@@ -984,6 +1047,48 @@ export declare class Image {
984
1047
  * @param radius The blur radius: the gaussian's standard deviation in pixels, like CSS' blur()
985
1048
  */
986
1049
  blur(radius: number): this;
1050
+ /**
1051
+ * Reduces the image to a palette of at most 256 colors (or a fixed one), in place, optionally dithered, e.g.
1052
+ * `image.quantize({ colors: 16, dither: 'floyd-steinberg' })` or `image.quantize({ palette: [0x0f380fff, 0x306230ff,
1053
+ * 0x8bac0fff, 0x9bbc0fff] })` for a Game Boy look. Transparent pixels (alpha 0) keep their color and don't count
1054
+ * towards the palette; the other pixels keep their alpha and only their RGB is reduced. The result is deterministic.
1055
+ * With a gain map (an HDR image), the HDR highlights are dropped, like {@link Image.invert} does: the map is neutral
1056
+ * afterwards. Frames quantize their own pixels
1057
+ * @param options See {@link QuantizeOptions}
1058
+ */
1059
+ quantize(options?: QuantizeOptions): this;
1060
+ /**
1061
+ * Mixes the colors of every pixel with a color matrix, like SVG's `feColorMatrix`: the new red, green, blue and alpha
1062
+ * are each a sum of the old red, green, blue and alpha times a factor, plus an offset. Greyscale, sepia, tints,
1063
+ * swapped channels, color blindness simulation or a mix of those in one pass.
1064
+ *
1065
+ * The values are 20 numbers, four rows of `[red, green, blue, alpha, offset]` for the new red, green, blue and alpha,
1066
+ * with the colors and the offsets as 0 to 1 (like CSS and SVG): `[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0,
1067
+ * 0, 0, 0, 1, 0]` changes nothing, `[0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]` swaps red and
1068
+ * blue. Nine numbers are the first three rows without the alpha and the offsets (the alpha stays as it is). The
1069
+ * colors are the sRGB values, not premultiplied, and the results are clamped. With a gain map (an HDR image), the
1070
+ * HDR highlights follow the change as they do for other color changes
1071
+ * @param matrix The 9 or 20 values
1072
+ */
1073
+ colorMatrix(matrix: ArrayLike<number>): this;
1074
+ /**
1075
+ * Moves every point of the image with an affine transform, in one resampling: rotation, scaling, skew, flips and
1076
+ * shifts in any mix and around any point. The six numbers are SVG's `matrix(a b c d e f)`: a point (x, y) of the
1077
+ * image ends up at (a x + c y + e, b x + d y + f), with y pointing down.
1078
+ * ```ts
1079
+ * image.transform([1, 0, Math.tan(-0.3), 1, 0, 0]); // slanted like italics, around the middle
1080
+ * image.transform([0.5, 0, 0, 0.5, 0, 0], { origin: { x: 0, y: 0 } }); // half the size
1081
+ * image.transform([-1, 0, 0, 1, 0, 0]); // flipped horizontally
1082
+ * const a = Math.PI / 6;
1083
+ * image.transform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]); // turned 30° clockwise
1084
+ * ```
1085
+ * The image grows to hold the result (`expand: false` keeps its size), so a shift only shows with `expand: false`.
1086
+ * The edges fade, like the pixels outside were transparent. A transform that flattens the image (a factor of 0) is
1087
+ * refused. With a gain map (an HDR image), the map moves with the image
1088
+ * @param matrix The six values [a, b, c, d, e, f]
1089
+ * @param options See {@link TransformOptions}
1090
+ */
1091
+ transform(matrix: ArrayLike<number>, options?: TransformOptions): this;
987
1092
  /**
988
1093
  * Adds a shadow behind the image, shaped by its alpha: a drop shadow with an offset, or a glow without one
989
1094
  * (`image.dropShadow({ blur: 8, color: 0xff2fb9ff })`, with `spread` to make it stronger). The image grows to fit
@@ -1245,7 +1350,15 @@ export declare class Image {
1245
1350
  * Creates a new image from the given SVG
1246
1351
  * Supports shapes, paths, transforms, use/symbol, CSS styles, gradients, patterns, strokes, markers, clip paths,
1247
1352
  * masks, opacity, blend modes, filters (all primitives and the filter functions) and images embedded as data URIs
1248
- * (PNG, JPEG, GIF, WebP, SVG), and text with the given or embedded fonts (see {@link SVGOptions.fonts})
1353
+ * (PNG, JPEG, GIF, WebP, SVG) or given with {@link SVGOptions.images}, and text with the given or embedded fonts
1354
+ * (see {@link SVGOptions.fonts}). Hrefs are resolved from the options and the data URIs only, never from files or URLs.
1355
+ * @example
1356
+ * ```ts
1357
+ * const logo = await Image.renderSVG(
1358
+ * '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><image href="logo.png" width="64" height="64"/></svg>',
1359
+ * { images: { 'logo.png': logoPNG } } // (the PNG's bytes, e.g. from a fetch or a file you read)
1360
+ * );
1361
+ * ```
1249
1362
  * @param svg The SVG content
1250
1363
  * @param options See {@link SVGOptions}
1251
1364
  * @return The rendered SVG graphic
package/dist/image.js CHANGED
@@ -35,6 +35,8 @@ import { isOptions, finite, color as checkColor, quality as checkQuality, effort
35
35
  import { MAX_PIXELS, decoding } from "./util/limits.js";
36
36
  import { GainMap } from "./gainmap.js";
37
37
  import * as gain from "./util/gain.js";
38
+ import { multiply, invert } from "./util/matrix.js";
39
+ import { sampleAffine } from "./util/affine.js";
38
40
  import * as gainMapCodec from "./codecs/gainmap.js";
39
41
  export class ResizeModes {
40
42
  static NEAREST_NEIGHBOR = 'nearest-neighbor';
@@ -50,6 +52,8 @@ export class SVGScaleModes {
50
52
  static HEIGHT = 'height';
51
53
  constructor() { }
52
54
  }
55
+ const DITHER_METHODS = ['none', 'floyd-steinberg', 'atkinson', 'ordered'];
56
+ const TRANSFORM_MODES = ['nearest-neighbor', 'bilinear', 'bicubic'];
53
57
  function featureList(features) {
54
58
  if (typeof features !== 'object' || features === null)
55
59
  throw new TypeError('Features must be an object');
@@ -835,6 +839,128 @@ export class Image {
835
839
  unpremultiply(pixels, this.bitmap);
836
840
  return this;
837
841
  }
842
+ quantize(options = {}) {
843
+ if (typeof options !== 'object' || options === null)
844
+ throw new TypeError('quantize takes an options object');
845
+ const { colors, palette, dither = 'none', ditherStrength = 1 } = options;
846
+ if (colors !== undefined && palette !== undefined)
847
+ throw new TypeError('quantize takes colors or palette, not both');
848
+ let fixed = null, count = 256;
849
+ if (palette !== undefined) {
850
+ if (!Array.isArray(palette))
851
+ throw new TypeError('palette has to be an array of colors');
852
+ if (palette.length < 1 || palette.length > 256)
853
+ throw new RangeError(`palette needs 1 to 256 colors, not ${palette.length}`);
854
+ const packed = new Uint8Array(palette.length * 3);
855
+ palette.forEach((color, i) => {
856
+ const value = checkColor(color, 'palette color');
857
+ if (!Number.isInteger(value) || value < 0 || value > 0xffffffff)
858
+ throw new RangeError(`Invalid palette color: ${color}`);
859
+ packed[i * 3] = value >>> 24;
860
+ packed[i * 3 + 1] = value >>> 16 & 255;
861
+ packed[i * 3 + 2] = value >>> 8 & 255;
862
+ });
863
+ fixed = packed;
864
+ }
865
+ else if (colors !== undefined) {
866
+ count = finite(colors, 'colors');
867
+ if (!Number.isInteger(count) || count < 2 || count > 256)
868
+ throw new RangeError(`colors must be an integer from 2 to 256, not ${colors}`);
869
+ }
870
+ if (!DITHER_METHODS.includes(dither))
871
+ throw new TypeError(`dither must be one of ${DITHER_METHODS.map(name => `'${name}'`).join(', ')}, not ${String(dither)}`);
872
+ const strength = finite(ditherStrength, 'ditherStrength');
873
+ if (strength < 0 || strength > 1)
874
+ throw new RangeError(`ditherStrength must be 0-1, not ${ditherStrength}`);
875
+ const reduce = (image) => {
876
+ const bytes = image.__bytes__();
877
+ const table = fixed ?? quantize.buildPalette(bytes, count, 1);
878
+ quantize.applyPalette(bytes, image.width, image.height, table, dither, strength);
879
+ };
880
+ if (this.__gain_map__)
881
+ return this.__unboost__(reduce);
882
+ reduce(this);
883
+ return this;
884
+ }
885
+ colorMatrix(matrix) {
886
+ if (matrix === null || typeof matrix !== 'object' || (matrix.length !== 9 && matrix.length !== 20))
887
+ throw new RangeError('A color matrix has 9 or 20 values');
888
+ const m = new Float64Array(20);
889
+ const value = (v) => finite(typeof v === 'number' ? v : NaN, 'color matrix value');
890
+ if (matrix.length === 20)
891
+ for (let i = 0; i < 20; i++)
892
+ m[i] = value(matrix[i]);
893
+ else
894
+ for (let row = 0; row < 3; row++)
895
+ for (let column = 0; column < 3; column++)
896
+ m[row * 5 + column] = value(matrix[row * 3 + column]);
897
+ if (matrix.length === 9)
898
+ m[18] = 1;
899
+ if (this.__gain_map__)
900
+ return this.__recolor__(image => image.colorMatrix(m));
901
+ const bitmap = this.bitmap;
902
+ for (let i = 0; i < bitmap.length; i += 4) {
903
+ const r = bitmap[i], g = bitmap[i + 1], b = bitmap[i + 2], a = bitmap[i + 3];
904
+ bitmap[i] = m[0] * r + m[1] * g + m[2] * b + m[3] * a + m[4] * 255;
905
+ bitmap[i + 1] = m[5] * r + m[6] * g + m[7] * b + m[8] * a + m[9] * 255;
906
+ bitmap[i + 2] = m[10] * r + m[11] * g + m[12] * b + m[13] * a + m[14] * 255;
907
+ bitmap[i + 3] = m[15] * r + m[16] * g + m[17] * b + m[18] * a + m[19] * 255;
908
+ }
909
+ return this;
910
+ }
911
+ transform(matrix, options = {}) {
912
+ if (matrix === null || typeof matrix !== 'object' || matrix.length !== 6)
913
+ throw new RangeError('A transform has 6 values: [a, b, c, d, e, f]');
914
+ const values = Array.from({ length: 6 }, (_, i) => finite(typeof matrix[i] === 'number' ? matrix[i] : NaN, 'transform value'));
915
+ if (typeof options !== 'object' || options === null)
916
+ throw new TypeError('transform takes an options object');
917
+ const { origin = {}, expand = true, mode = 'bilinear' } = options;
918
+ if (!TRANSFORM_MODES.includes(mode))
919
+ throw new TypeError(`transform mode must be one of ${TRANSFORM_MODES.map(name => `'${name}'`).join(', ')}, not ${String(mode)}`);
920
+ const { x: pivotX = this.width / 2, y: pivotY = this.height / 2 } = origin;
921
+ finite(pivotX, 'origin x');
922
+ finite(pivotY, 'origin y');
923
+ const around = multiply(multiply([1, 0, 0, 1, pivotX, pivotY], values), [1, 0, 0, 1, -pivotX, -pivotY]);
924
+ const inverse = invert(around);
925
+ if (!inverse)
926
+ throw new RangeError('The transform has to be invertible: it can\'t flatten the image');
927
+ const { width, height } = this;
928
+ let left = 0, top = 0, outWidth = width, outHeight = height;
929
+ if (expand) {
930
+ const xs = [], ys = [];
931
+ for (const [x, y] of [[0, 0], [width, 0], [0, height], [width, height]]) {
932
+ xs.push(around[0] * x + around[2] * y + around[4]);
933
+ ys.push(around[1] * x + around[3] * y + around[5]);
934
+ }
935
+ const minX = Math.min(...xs), maxX = Math.max(...xs), minY = Math.min(...ys), maxY = Math.max(...ys);
936
+ outWidth = Math.max(1, Math.round(maxX - minX));
937
+ outHeight = Math.max(1, Math.round(maxY - minY));
938
+ left = minX - (outWidth - (maxX - minX)) / 2;
939
+ top = minY - (outHeight - (maxY - minY)) / 2;
940
+ const room = this.__room__();
941
+ if (left < -room.left) {
942
+ left = -room.left;
943
+ outWidth = Math.max(1, Math.round(maxX - left));
944
+ }
945
+ if (top < -room.top) {
946
+ top = -room.top;
947
+ outHeight = Math.max(1, Math.round(maxY - top));
948
+ }
949
+ if (outWidth * outHeight > MAX_PIXELS)
950
+ throw new RangeError(`The transformed image would have ${outWidth}x${outHeight} pixels, more than the ${MAX_PIXELS} allowed`);
951
+ }
952
+ const out = new Image(outWidth, outHeight);
953
+ sampleAffine(this.bitmap, width, height, out.bitmap, outWidth, outHeight, inverse, left, top, mode);
954
+ const scale = Math.sqrt(Math.abs(around[0] * around[3] - around[1] * around[2]));
955
+ this.__gain_map__?.__transform__(width, height, outWidth, outHeight, (X, Y) => {
956
+ const x = X + left, y = Y + top;
957
+ return [inverse[0] * x + inverse[2] * y + inverse[4], inverse[1] * x + inverse[3] * y + inverse[5]];
958
+ }, scale);
959
+ this.__apply__(out);
960
+ if (left || top)
961
+ this.__grown__(-Math.round(left), -Math.round(top));
962
+ return this;
963
+ }
838
964
  dropShadow(options = {}) {
839
965
  const { x = 0, y = 0, blur = 0, spread = 0, color = 0x00000080, expand = true } = options;
840
966
  finite(x, 'x');
@@ -1480,7 +1606,7 @@ export class Image {
1480
1606
  static SVG_MODE_WIDTH = 2;
1481
1607
  static SVG_MODE_HEIGHT = 3;
1482
1608
  static async renderSVG(svg, sizeOrOptions = 1, modeArgument = SVGScaleModes.SCALE) {
1483
- const { size = 1, mode: givenMode = SVGScaleModes.SCALE, fonts = [] } = isOptions(sizeOrOptions) ? sizeOrOptions : { size: sizeOrOptions, mode: modeArgument };
1609
+ const { size = 1, mode: givenMode = SVGScaleModes.SCALE, fonts = [], images: givenImages = {} } = isOptions(sizeOrOptions) ? sizeOrOptions : { size: sizeOrOptions, mode: modeArgument };
1484
1610
  const mode = LEGACY_SVG_MODES.get(givenMode) ?? givenMode;
1485
1611
  if (mode !== 'scale' && mode !== 'width' && mode !== 'height')
1486
1612
  throw new Error('Invalid SVG scaling mode');
@@ -1489,18 +1615,31 @@ export class Image {
1489
1615
  throw new RangeError('SVG scale must be > 0');
1490
1616
  if (mode !== SVGScaleModes.SCALE && size < 1)
1491
1617
  throw new RangeError('SVG size must be >= 1');
1618
+ if (typeof givenImages !== 'object' || givenImages === null || Array.isArray(givenImages) || givenImages instanceof Map)
1619
+ throw new TypeError('SVG images must be an object of hrefs to image data');
1620
+ const given = new Map();
1621
+ for (const href of Object.keys(givenImages)) {
1622
+ const value = givenImages[href];
1623
+ if (!(value instanceof Image) && !(value instanceof ArrayBuffer || ArrayBuffer.isView(value)))
1624
+ throw new TypeError(`SVG image ${JSON.stringify(href)} must be BinaryData or an Image`);
1625
+ given.set(href, value);
1626
+ }
1492
1627
  const source = typeof svg === 'string' ? svg : view(svg);
1493
1628
  const images = new Map();
1494
- for (const { href, data } of svgRenderer.embeddedImages(source)) {
1495
- if (images.has(href))
1629
+ for (const { href, data } of svgRenderer.imageReferences(source)) {
1630
+ const value = given.get(href) ?? data;
1631
+ if (!value)
1496
1632
  continue;
1497
1633
  try {
1498
- if (ImageType.getType(data) === 'gif') {
1499
- const decoded = gif.decode(data, true);
1634
+ if (value instanceof Image) {
1635
+ images.set(href, { width: value.width, height: value.height, pixels: value.bitmap });
1636
+ }
1637
+ else if (ImageType.getType(value) === 'gif') {
1638
+ const decoded = gif.decode(view(value), true);
1500
1639
  images.set(href, { width: decoded.width, height: decoded.height, pixels: gif.composite(decoded)[0].pixels });
1501
1640
  }
1502
1641
  else {
1503
- const image = await Image.decode(data);
1642
+ const image = await Image.decode(value);
1504
1643
  images.set(href, { width: image.width, height: image.height, pixels: image.bitmap });
1505
1644
  }
1506
1645
  }
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ import { GIF } from './gif.js';
4
4
  import { Animation, AnimationDecodeOptions } from './animation.js';
5
5
  export { Image, ResizeModes, SVGScaleModes } from './image.js';
6
6
  export { Colors } from './colors.js';
7
- export type { Color, ColorFunction, ResizeMode, SVGScaleMode, PNGMetadata, TextStyle, DecodeOptions, CompositeOptions, BlendMode, CropCircleOptions, DominantColorOptions, RotateOptions, ColorToAlphaOptions, ResizeOptions, ResizeToOptions, AdjustOptions, SharpenOptions, PNGEncodeOptions, JPEGEncodeOptions, WebPEncodeOptions, AVIFEncodeOptions, JXLEncodeOptions, EncodeOptions, SVGOptions, TextOptions, RenderTextOptions, ShadowOptions, OutlineOptions, GradientOptions, LinearGradientOptions, RadialGradientOptions, RoundCornersOptions, FisheyeOptions, TrimOptions } from './image.js';
7
+ export type { Color, ColorFunction, ResizeMode, SVGScaleMode, PNGMetadata, TextStyle, DecodeOptions, CompositeOptions, BlendMode, CropCircleOptions, DominantColorOptions, RotateOptions, ColorToAlphaOptions, ResizeOptions, ResizeToOptions, AdjustOptions, SharpenOptions, PNGEncodeOptions, JPEGEncodeOptions, WebPEncodeOptions, AVIFEncodeOptions, JXLEncodeOptions, EncodeOptions, SVGOptions, TextOptions, RenderTextOptions, ShadowOptions, OutlineOptions, QuantizeOptions, TransformOptions, TransformMode, GradientOptions, LinearGradientOptions, RadialGradientOptions, RoundCornersOptions, FisheyeOptions, TrimOptions } from './image.js';
8
8
  export { Frame, FrameDisposalModes } from './frame.js';
9
9
  export type { FrameDisposalModeName, FrameDisposalModeId, FrameOptions } from './frame.js';
10
10
  export { GainMap } from './gainmap.js';
@@ -1,18 +1,8 @@
1
1
  import { parsePalette } from "./color.js";
2
+ import { multiply, invert } from "../util/matrix.js";
2
3
  const MAX_DEPTH = 64;
3
4
  const SAMPLES = 4;
4
5
  const MAX_PIXELS = 1 << 20;
5
- const multiply = (m, n) => [
6
- m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1],
7
- m[0] * n[2] + m[2] * n[3], m[1] * n[2] + m[3] * n[3],
8
- m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5]
9
- ];
10
- const invert = (m) => {
11
- const det = m[0] * m[3] - m[1] * m[2];
12
- if (!det)
13
- return null;
14
- return [m[3] / det, -m[1] / det, -m[2] / det, m[0] / det, (m[2] * m[5] - m[3] * m[4]) / det, (m[1] * m[4] - m[0] * m[5]) / det];
15
- };
16
6
  const around = (cx, cy, m) => multiply(multiply([1, 0, 0, 1, cx, cy], m), [1, 0, 0, 1, -cx, -cy]);
17
7
  export function parsePaintGlyphs(font) {
18
8
  const colr = font.tables.COLR?.offset;
@@ -12,6 +12,7 @@ import { graphemeBoundaries, scripts } from "./segment.js";
12
12
  import { loadFont } from "./text.js";
13
13
  import { parseColorLayers, parseBitmaps } from "./color.js";
14
14
  import { parsePaintGlyphs } from "./colr.js";
15
+ import { multiply } from "../util/matrix.js";
15
16
  const faces = new WeakMap();
16
17
  function names(font, ids) {
17
18
  const table = font.tables.name;
@@ -264,13 +265,6 @@ export function parseFontFamilies(value) {
264
265
  return families;
265
266
  }
266
267
  const IDENTITY = [1, 0, 0, 1, 0, 0];
267
- function multiply(m, n) {
268
- return [
269
- m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1],
270
- m[0] * n[2] + m[2] * n[3], m[1] * n[2] + m[3] * n[3],
271
- m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5],
272
- ];
273
- }
274
268
  const translate = (m, x, y) => multiply(m, [1, 0, 0, 1, x, y]);
275
269
  const scale = (m, x, y) => multiply(m, [x, 0, 0, y, 0, 0]);
276
270
  function rotate(m, degrees, cx = 0, cy = 0) {
@@ -14,6 +14,7 @@ import { decode as decodeUTF8, encode as encodeUTF8 } from "../util/utf8.js";
14
14
  import { base64 } from "../util/bytes.js";
15
15
  import { gunzip } from "../codecs/zlib.js";
16
16
  import { applyFilter } from "./filter.js";
17
+ import { multiply, invert } from "../util/matrix.js";
17
18
  import { BLEND_MODES, blendPixel } from "./blend.js";
18
19
  import { fontFace, layOutText, parseFontFamilies, parseVariationSettings, pathLength, placeOutline, colorTablesOf } from "./svg-text.js";
19
20
  import { rasterizeGlyph } from "./text.js";
@@ -152,7 +153,7 @@ function nestedSvg(href) {
152
153
  return null;
153
154
  }
154
155
  }
155
- export function embeddedImages(source) {
156
+ export function imageReferences(source) {
156
157
  const found = [], seen = new Set();
157
158
  const visit = (text, depth) => {
158
159
  let root;
@@ -173,12 +174,17 @@ export function embeddedImages(source) {
173
174
  continue;
174
175
  seen.add(href);
175
176
  const uri = dataURI(href);
176
- if (!uri)
177
+ if (!uri) {
178
+ found.push({ href });
177
179
  continue;
180
+ }
178
181
  if (RASTER_TYPES.test(uri.type) || (uri.type === 'text/plain' && isRaster(uri.data)))
179
182
  found.push({ href, data: uri.data });
180
- else if ((uri.type === 'image/svg+xml' || uri.type === 'text/plain') && depth < 8)
181
- visit(() => svgText(uri.data), depth + 1);
183
+ else {
184
+ found.push({ href });
185
+ if ((uri.type === 'image/svg+xml' || uri.type === 'text/plain') && depth < 8)
186
+ visit(() => svgText(uri.data), depth + 1);
187
+ }
182
188
  }
183
189
  };
184
190
  visit(() => typeof source === 'string' ? source : decodeUTF8(source), 0);
@@ -3334,19 +3340,6 @@ function strokePolygons(subpaths, halfWidth, cap, join, miterLimit, tolerance) {
3334
3340
  }
3335
3341
  return polygons;
3336
3342
  }
3337
- function multiply(a, b) {
3338
- return [
3339
- a[0] * b[0] + a[2] * b[1], a[1] * b[0] + a[3] * b[1],
3340
- a[0] * b[2] + a[2] * b[3], a[1] * b[2] + a[3] * b[3],
3341
- a[0] * b[4] + a[2] * b[5] + a[4], a[1] * b[4] + a[3] * b[5] + a[5]
3342
- ];
3343
- }
3344
- function invert(m) {
3345
- const det = m[0] * m[3] - m[1] * m[2];
3346
- if (!det || !isFinite(det))
3347
- return null;
3348
- return [m[3] / det, -m[1] / det, -m[2] / det, m[0] / det, (m[2] * m[5] - m[3] * m[4]) / det, (m[1] * m[4] - m[0] * m[5]) / det];
3349
- }
3350
3343
  function parseTransform(value) {
3351
3344
  let matrix = [1, 0, 0, 1, 0, 0];
3352
3345
  const functions = /(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g;
@@ -0,0 +1,80 @@
1
+ function cubic(t, out) {
2
+ const t2 = t * t, t3 = t2 * t;
3
+ out[0] = -0.5 * t3 + t2 - 0.5 * t;
4
+ out[1] = 1.5 * t3 - 2.5 * t2 + 1;
5
+ out[2] = -1.5 * t3 + 2 * t2 + 0.5 * t;
6
+ out[3] = 0.5 * t3 - 0.5 * t2;
7
+ }
8
+ export function sampleAffine(src, width, height, out, outWidth, outHeight, inverse, left, top, mode) {
9
+ const [a, b, c, d, e, f] = inverse;
10
+ const wx = new Float64Array(4), wy = new Float64Array(4);
11
+ for (let oy = 0; oy < outHeight; oy++) {
12
+ const y = oy + top + 0.5;
13
+ const sx0 = a * (left + 0.5) + c * y + e, sy0 = b * (left + 0.5) + d * y + f;
14
+ for (let ox = 0; ox < outWidth; ox++) {
15
+ const sx = sx0 + a * ox, sy = sy0 + b * ox;
16
+ const o = 4 * (oy * outWidth + ox);
17
+ if (mode === 'nearest-neighbor') {
18
+ const ix = Math.floor(sx), iy = Math.floor(sy);
19
+ if (ix < 0 || iy < 0 || ix >= width || iy >= height)
20
+ continue;
21
+ const i = 4 * (iy * width + ix);
22
+ out[o] = src[i];
23
+ out[o + 1] = src[i + 1];
24
+ out[o + 2] = src[i + 2];
25
+ out[o + 3] = src[i + 3];
26
+ continue;
27
+ }
28
+ const u = sx - 0.5, v = sy - 0.5;
29
+ const x0 = Math.floor(u), y0 = Math.floor(v), fx = u - x0, fy = v - y0;
30
+ let r = 0, g = 0, bl = 0, alpha = 0;
31
+ if (mode === 'bilinear') {
32
+ if (x0 < -1 || y0 < -1 || x0 >= width || y0 >= height)
33
+ continue;
34
+ for (let j = 0; j < 2; j++) {
35
+ const yy = y0 + j;
36
+ if (yy < 0 || yy >= height)
37
+ continue;
38
+ const weightY = j ? fy : 1 - fy;
39
+ for (let i = 0; i < 2; i++) {
40
+ const xx = x0 + i;
41
+ if (xx < 0 || xx >= width)
42
+ continue;
43
+ const p = 4 * (yy * width + xx), weight = (i ? fx : 1 - fx) * weightY * src[p + 3];
44
+ r += weight * src[p];
45
+ g += weight * src[p + 1];
46
+ bl += weight * src[p + 2];
47
+ alpha += weight;
48
+ }
49
+ }
50
+ }
51
+ else {
52
+ if (x0 < -2 || y0 < -2 || x0 > width || y0 > height)
53
+ continue;
54
+ cubic(fx, wx);
55
+ cubic(fy, wy);
56
+ for (let j = 0; j < 4; j++) {
57
+ const yy = y0 - 1 + j;
58
+ if (yy < 0 || yy >= height)
59
+ continue;
60
+ for (let i = 0; i < 4; i++) {
61
+ const xx = x0 - 1 + i;
62
+ if (xx < 0 || xx >= width)
63
+ continue;
64
+ const p = 4 * (yy * width + xx), weight = wx[i] * wy[j] * src[p + 3];
65
+ r += weight * src[p];
66
+ g += weight * src[p + 1];
67
+ bl += weight * src[p + 2];
68
+ alpha += weight;
69
+ }
70
+ }
71
+ }
72
+ if (alpha <= 0)
73
+ continue;
74
+ out[o] = r / alpha;
75
+ out[o + 1] = g / alpha;
76
+ out[o + 2] = bl / alpha;
77
+ out[o + 3] = alpha;
78
+ }
79
+ }
80
+ }
@@ -0,0 +1,14 @@
1
+ export const IDENTITY = [1, 0, 0, 1, 0, 0];
2
+ export function multiply(a, b) {
3
+ return [
4
+ a[0] * b[0] + a[2] * b[1], a[1] * b[0] + a[3] * b[1],
5
+ a[0] * b[2] + a[2] * b[3], a[1] * b[2] + a[3] * b[3],
6
+ a[0] * b[4] + a[2] * b[5] + a[4], a[1] * b[4] + a[3] * b[5] + a[5]
7
+ ];
8
+ }
9
+ export function invert(m) {
10
+ const det = m[0] * m[3] - m[1] * m[2];
11
+ if (!det || !isFinite(det))
12
+ return null;
13
+ return [m[3] / det, -m[1] / det, -m[2] / det, m[0] / det, (m[2] * m[5] - m[3] * m[4]) / det, (m[1] * m[4] - m[0] * m[5]) / det];
14
+ }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = '3.19.0';
1
+ export const VERSION = '3.20.0';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "imagescript",
3
- "version": "3.19.0",
3
+ "version": "3.20.0",
4
4
  "description": "Pure TypeScript image processing that runs everywhere",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",