imagescript 3.18.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.
- package/dist/codecs/quantize.js +83 -2
- package/dist/frame.js +7 -0
- package/dist/image.d.ts +209 -1
- package/dist/image.js +294 -8
- package/dist/index.d.ts +1 -1
- package/dist/render/colr.js +1 -11
- package/dist/render/svg-text.js +1 -7
- package/dist/render/svg.js +10 -17
- package/dist/util/affine.js +80 -0
- package/dist/util/matrix.js +14 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/codecs/quantize.js
CHANGED
|
@@ -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
|
|
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] <
|
|
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/frame.js
CHANGED
|
@@ -58,6 +58,13 @@ export class Frame extends Image {
|
|
|
58
58
|
clone() {
|
|
59
59
|
return Frame.from(this, { duration: this.duration, xOffset: this.xOffset, yOffset: this.yOffset, disposalMode: this.disposalMode });
|
|
60
60
|
}
|
|
61
|
+
__room__() {
|
|
62
|
+
return { left: this.xOffset, top: this.yOffset };
|
|
63
|
+
}
|
|
64
|
+
__grown__(left, top) {
|
|
65
|
+
this.xOffset -= left;
|
|
66
|
+
this.yOffset -= top;
|
|
67
|
+
}
|
|
61
68
|
trim(colorOrOptions, optionsArgument = {}) {
|
|
62
69
|
const { color, ...options } = isOptions(colorOrOptions) ? colorOrOptions : { ...optionsArgument, color: colorOrOptions ?? optionsArgument.color };
|
|
63
70
|
const bounds = this.__trim_bounds__(color, options);
|
package/dist/image.d.ts
CHANGED
|
@@ -113,6 +113,118 @@ 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
|
+
}
|
|
171
|
+
/** Options of {@link Image.dropShadow} */
|
|
172
|
+
export interface ShadowOptions {
|
|
173
|
+
/** How far to move the shadow to the right (negative values: to the left), in pixels. Default: `0` */
|
|
174
|
+
x?: number;
|
|
175
|
+
/** How far to move the shadow down (negative values: up), in pixels. Default: `0` */
|
|
176
|
+
y?: number;
|
|
177
|
+
/** How soft the shadow's edge is: the standard deviation of a gaussian blur in pixels, like {@link Image.blur}. Default: `0` */
|
|
178
|
+
blur?: number;
|
|
179
|
+
/** How far to grow the shadow's shape before blurring it, in pixels. Default: `0` */
|
|
180
|
+
spread?: number;
|
|
181
|
+
/** The shadow's color, its alpha is the shadow's opacity. Default: `0x00000080` (50% black) */
|
|
182
|
+
color?: Color;
|
|
183
|
+
/**
|
|
184
|
+
* Whether to make the image larger so the shadow isn't cut off. Without it, the image keeps its size and the part
|
|
185
|
+
* of the shadow outside is lost. Default: `true`
|
|
186
|
+
*/
|
|
187
|
+
expand?: boolean;
|
|
188
|
+
}
|
|
189
|
+
/** Options of {@link Image.outline} */
|
|
190
|
+
export interface OutlineOptions {
|
|
191
|
+
/** The outline's width in pixels. Default: `1` */
|
|
192
|
+
width?: number;
|
|
193
|
+
/** The outline's color. Default: `0x000000ff` */
|
|
194
|
+
color?: Color;
|
|
195
|
+
/**
|
|
196
|
+
* Whether to make the image larger so the outline isn't cut off. Without it, the image keeps its size and the
|
|
197
|
+
* outline is cut where the image ends. Default: `true`
|
|
198
|
+
*/
|
|
199
|
+
expand?: boolean;
|
|
200
|
+
}
|
|
201
|
+
/** The colors of a gradient, see {@link Image.linearGradient} */
|
|
202
|
+
export interface GradientOptions {
|
|
203
|
+
/**
|
|
204
|
+
* The colors along the gradient: their positions (0..1) and colors, like {@link Colors.gradient} takes them
|
|
205
|
+
* (`{ 0: 0xff0000ff, 0.5: 0xffff00ff, 1: 0x00ff00ff }`), or just the colors, evenly spaced
|
|
206
|
+
* (`[0xff0000ff, 0x00ff00ff]`)
|
|
207
|
+
*/
|
|
208
|
+
stops: Record<number, Color> | Color[];
|
|
209
|
+
}
|
|
210
|
+
/** Options of {@link Image.linearGradient} */
|
|
211
|
+
export interface LinearGradientOptions extends GradientOptions {
|
|
212
|
+
/**
|
|
213
|
+
* The direction of the gradient in degrees, like CSS' `linear-gradient()`: `0` goes up, `90` to the right, `180`
|
|
214
|
+
* down, `270` to the left. The first stop is at the start of the line through the center that touches the
|
|
215
|
+
* corners. Default: `180`
|
|
216
|
+
*/
|
|
217
|
+
angle?: number;
|
|
218
|
+
}
|
|
219
|
+
/** Options of {@link Image.radialGradient} */
|
|
220
|
+
export interface RadialGradientOptions extends GradientOptions {
|
|
221
|
+
/** The x position of the center in pixels. Default: the middle of the image */
|
|
222
|
+
x?: number;
|
|
223
|
+
/** The y position of the center in pixels. Default: the middle of the image */
|
|
224
|
+
y?: number;
|
|
225
|
+
/** The radius of the last stop in pixels. Default: the distance to the farthest corner */
|
|
226
|
+
radius?: number;
|
|
227
|
+
}
|
|
116
228
|
/** Options of {@link Image.encode} */
|
|
117
229
|
export interface PNGEncodeOptions {
|
|
118
230
|
/** The compression level (0-9), higher is smaller but slower. Default: `4` */
|
|
@@ -209,6 +321,14 @@ export interface SVGOptions {
|
|
|
209
321
|
* before these for their family names. Without any fonts text isn't rendered. Default: `[]`
|
|
210
322
|
*/
|
|
211
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>;
|
|
212
332
|
}
|
|
213
333
|
/** Options of {@link Image.renderText}: the text color and layout, and its style (see {@link TextStyle}) */
|
|
214
334
|
export interface TextOptions extends TextStyle {
|
|
@@ -558,6 +678,22 @@ export declare class Image {
|
|
|
558
678
|
* @group Deprecated
|
|
559
679
|
*/
|
|
560
680
|
static colorToRGB(color: Color): [r: number, g: number, b: number];
|
|
681
|
+
/**
|
|
682
|
+
* Creates an image with a linear gradient, like CSS' `linear-gradient()`
|
|
683
|
+
* @param width The image's width
|
|
684
|
+
* @param height The image's height
|
|
685
|
+
* @param options The colors and the direction, see {@link LinearGradientOptions}
|
|
686
|
+
* @returns The new image
|
|
687
|
+
*/
|
|
688
|
+
static linearGradient(width: number, height: number, options: LinearGradientOptions): Image;
|
|
689
|
+
/**
|
|
690
|
+
* Creates an image with a radial (circular) gradient, like CSS' `radial-gradient(circle)`
|
|
691
|
+
* @param width The image's width
|
|
692
|
+
* @param height The image's height
|
|
693
|
+
* @param options The colors and the circle, see {@link RadialGradientOptions}
|
|
694
|
+
* @returns The new image
|
|
695
|
+
*/
|
|
696
|
+
static radialGradient(width: number, height: number, options: RadialGradientOptions): Image;
|
|
561
697
|
/**
|
|
562
698
|
* Creates a multi-point gradient generator
|
|
563
699
|
* @param colors The gradient points to use (e.g. `{0: 0xff0000ff, 1: 0x00ff00ff}`)
|
|
@@ -788,6 +924,13 @@ export declare class Image {
|
|
|
788
924
|
* @param color The color to use, its alpha is ignored
|
|
789
925
|
*/
|
|
790
926
|
recolor(color: Color): this;
|
|
927
|
+
/**
|
|
928
|
+
* Sets the RGB of every pixel to the RGB of the same pixel of another image, keeping each pixel's own alpha. With a
|
|
929
|
+
* gradient this fills a shape with it, e.g. gradient text:
|
|
930
|
+
* `text.recolor(Image.linearGradient(text.width, text.height, { stops: [0x22d3eeff, 0xfb923cff], angle: 90 }))`
|
|
931
|
+
* @param colors The image to take the colors from, it has to have the same size. Its alpha is ignored
|
|
932
|
+
*/
|
|
933
|
+
recolor(colors: Image): this;
|
|
791
934
|
/**
|
|
792
935
|
* Scales the opacity of the image
|
|
793
936
|
* @param opacity The factor to multiply the opacity with (0..1 lowers it, >1 raises it, results are clamped)
|
|
@@ -904,6 +1047,63 @@ export declare class Image {
|
|
|
904
1047
|
* @param radius The blur radius: the gaussian's standard deviation in pixels, like CSS' blur()
|
|
905
1048
|
*/
|
|
906
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;
|
|
1092
|
+
/**
|
|
1093
|
+
* Adds a shadow behind the image, shaped by its alpha: a drop shadow with an offset, or a glow without one
|
|
1094
|
+
* (`image.dropShadow({ blur: 8, color: 0xff2fb9ff })`, with `spread` to make it stronger). The image grows to fit
|
|
1095
|
+
* the shadow, unless `expand` is `false`. Frames stay where they are (their offsets move with the growth), they only
|
|
1096
|
+
* grow up and left as far as their offset allows
|
|
1097
|
+
* @param options See {@link ShadowOptions}
|
|
1098
|
+
*/
|
|
1099
|
+
dropShadow(options?: ShadowOptions): this;
|
|
1100
|
+
/**
|
|
1101
|
+
* Draws an outline around the image's shape (its alpha): the sticker effect for cut-out images, or an outline for
|
|
1102
|
+
* text. The image grows to fit it, unless `expand` is `false`. Frames stay where they are (their offsets move with
|
|
1103
|
+
* the growth), they only grow up and left as far as their offset allows
|
|
1104
|
+
* @param options See {@link OutlineOptions}
|
|
1105
|
+
*/
|
|
1106
|
+
outline(options?: OutlineOptions): this;
|
|
907
1107
|
/**
|
|
908
1108
|
* Sharpens the image with an unsharp mask: the difference to a blurred copy is amplified
|
|
909
1109
|
* @param options See {@link SharpenOptions}
|
|
@@ -1150,7 +1350,15 @@ export declare class Image {
|
|
|
1150
1350
|
* Creates a new image from the given SVG
|
|
1151
1351
|
* Supports shapes, paths, transforms, use/symbol, CSS styles, gradients, patterns, strokes, markers, clip paths,
|
|
1152
1352
|
* masks, opacity, blend modes, filters (all primitives and the filter functions) and images embedded as data URIs
|
|
1153
|
-
* (PNG, JPEG, GIF, WebP, SVG), and text with the given or embedded 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
|
+
* ```
|
|
1154
1362
|
* @param svg The SVG content
|
|
1155
1363
|
* @param options See {@link SVGOptions}
|
|
1156
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');
|
|
@@ -154,6 +158,34 @@ export class Image {
|
|
|
154
158
|
static colorToRGB(color) {
|
|
155
159
|
return Colors.toRGB(color);
|
|
156
160
|
}
|
|
161
|
+
static linearGradient(width, height, options) {
|
|
162
|
+
const { stops, angle = 180 } = options;
|
|
163
|
+
const color = gradientFunction(stops);
|
|
164
|
+
finite(angle, 'angle');
|
|
165
|
+
const image = new Image(width, height);
|
|
166
|
+
const radians = angle * Math.PI / 180;
|
|
167
|
+
const dx = Math.sin(radians), dy = -Math.cos(radians);
|
|
168
|
+
const length = Math.abs(width * dx) + Math.abs(height * dy);
|
|
169
|
+
const cx = width / 2, cy = height / 2, bitmap = new DataView(image.bitmap.buffer, image.bitmap.byteOffset, image.bitmap.byteLength);
|
|
170
|
+
for (let y = 0, i = 0; y < height; y++)
|
|
171
|
+
for (let x = 0; x < width; x++, i += 4)
|
|
172
|
+
bitmap.setUint32(i, color(((x + 0.5 - cx) * dx + (y + 0.5 - cy) * dy) / length + 0.5), false);
|
|
173
|
+
return image;
|
|
174
|
+
}
|
|
175
|
+
static radialGradient(width, height, options) {
|
|
176
|
+
const { stops, x: cx = width / 2, y: cy = height / 2, radius = Math.hypot(Math.max(cx, width - cx), Math.max(cy, height - cy)) } = options;
|
|
177
|
+
const color = gradientFunction(stops);
|
|
178
|
+
finite(cx, 'x');
|
|
179
|
+
finite(cy, 'y');
|
|
180
|
+
if (!(finite(radius, 'radius') > 0))
|
|
181
|
+
throw new RangeError('Invalid radius');
|
|
182
|
+
const image = new Image(width, height);
|
|
183
|
+
const bitmap = new DataView(image.bitmap.buffer, image.bitmap.byteOffset, image.bitmap.byteLength);
|
|
184
|
+
for (let y = 0, i = 0; y < height; y++)
|
|
185
|
+
for (let x = 0; x < width; x++, i += 4)
|
|
186
|
+
bitmap.setUint32(i, color(Math.hypot(x + 0.5 - cx, y + 0.5 - cy) / radius), false);
|
|
187
|
+
return image;
|
|
188
|
+
}
|
|
157
189
|
static gradient(colors) {
|
|
158
190
|
return Colors.gradient(colors);
|
|
159
191
|
}
|
|
@@ -508,10 +540,24 @@ export class Image {
|
|
|
508
540
|
}
|
|
509
541
|
return this;
|
|
510
542
|
}
|
|
511
|
-
recolor(
|
|
543
|
+
recolor(colorOrImage) {
|
|
544
|
+
if (colorOrImage instanceof Image) {
|
|
545
|
+
const colors = colorOrImage;
|
|
546
|
+
if (colors.width !== this.width || colors.height !== this.height)
|
|
547
|
+
throw new RangeError(`The image to take the colors from has to be ${this.width}x${this.height}, not ${colors.width}x${colors.height}`);
|
|
548
|
+
if (this.__gain_map__)
|
|
549
|
+
return this.__recolor__(image => image.recolor(image.width === colors.width && image.height === colors.height ? colors : colors.clone().resize(image.width, image.height)));
|
|
550
|
+
const from = colors.bitmap, to = this.bitmap;
|
|
551
|
+
for (let i = 0; i < to.length; i += 4) {
|
|
552
|
+
to[i] = from[i];
|
|
553
|
+
to[i + 1] = from[i + 1];
|
|
554
|
+
to[i + 2] = from[i + 2];
|
|
555
|
+
}
|
|
556
|
+
return this;
|
|
557
|
+
}
|
|
558
|
+
const color = checkColor(colorOrImage);
|
|
512
559
|
if (this.__gain_map__)
|
|
513
560
|
return this.__recolor__(image => image.recolor(color));
|
|
514
|
-
color = checkColor(color);
|
|
515
561
|
const r = color >>> 24, g = color >> 16 & 0xff, b = color >> 8 & 0xff;
|
|
516
562
|
for (let i = 0; i < this.bitmap.length; i += 4) {
|
|
517
563
|
this.bitmap[i] = r;
|
|
@@ -793,6 +839,225 @@ export class Image {
|
|
|
793
839
|
unpremultiply(pixels, this.bitmap);
|
|
794
840
|
return this;
|
|
795
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
|
+
}
|
|
964
|
+
dropShadow(options = {}) {
|
|
965
|
+
const { x = 0, y = 0, blur = 0, spread = 0, color = 0x00000080, expand = true } = options;
|
|
966
|
+
finite(x, 'x');
|
|
967
|
+
finite(y, 'y');
|
|
968
|
+
if (finite(blur, 'blur') < 0)
|
|
969
|
+
throw new RangeError('Invalid blur radius');
|
|
970
|
+
if (finite(spread, 'spread') < 0)
|
|
971
|
+
throw new RangeError('Invalid spread');
|
|
972
|
+
const [r, g, b, a] = Colors.toRGBA(checkColor(color));
|
|
973
|
+
const reach = spread + 3 * blur, margin = Math.ceil(reach) + 1;
|
|
974
|
+
const layer = this.__shape_layer__(margin);
|
|
975
|
+
const width = layer.width;
|
|
976
|
+
const coverage = new Uint8Array(width * layer.height);
|
|
977
|
+
for (let i = 0; i < coverage.length; i++)
|
|
978
|
+
coverage[i] = layer.bitmap[i * 4 + 3];
|
|
979
|
+
const grown = spread > 0 ? outline(coverage, width, layer.height, spread) : null;
|
|
980
|
+
const bitmap = layer.bitmap;
|
|
981
|
+
for (let i = 0; i < coverage.length; i++) {
|
|
982
|
+
bitmap[i * 4] = r;
|
|
983
|
+
bitmap[i * 4 + 1] = g;
|
|
984
|
+
bitmap[i * 4 + 2] = b;
|
|
985
|
+
bitmap[i * 4 + 3] = (grown ? grown[i] * 255 : coverage[i]) * a / 255;
|
|
986
|
+
}
|
|
987
|
+
if (blur > 0) {
|
|
988
|
+
layer.blur(blur);
|
|
989
|
+
for (let i = 0; i < coverage.length; i++) {
|
|
990
|
+
if (!bitmap[i * 4 + 3])
|
|
991
|
+
continue;
|
|
992
|
+
bitmap[i * 4] = r;
|
|
993
|
+
bitmap[i * 4 + 1] = g;
|
|
994
|
+
bitmap[i * 4 + 2] = b;
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
const room = this.__room__();
|
|
998
|
+
return this.__under__(layer, x - margin, y - margin, expand ? {
|
|
999
|
+
left: Math.min(room.left, Math.max(0, Math.ceil(reach - x))),
|
|
1000
|
+
top: Math.min(room.top, Math.max(0, Math.ceil(reach - y))),
|
|
1001
|
+
right: Math.max(0, Math.ceil(reach + x)),
|
|
1002
|
+
bottom: Math.max(0, Math.ceil(reach + y))
|
|
1003
|
+
} : { left: 0, top: 0, right: 0, bottom: 0 });
|
|
1004
|
+
}
|
|
1005
|
+
outline(options = {}) {
|
|
1006
|
+
const { width = 1, color = 0x000000ff, expand = true } = options;
|
|
1007
|
+
if (finite(width, 'outline width') < 0)
|
|
1008
|
+
throw new RangeError('Invalid outline width');
|
|
1009
|
+
const [r, g, b, a] = Colors.toRGBA(checkColor(color));
|
|
1010
|
+
if (width === 0)
|
|
1011
|
+
return this;
|
|
1012
|
+
const margin = Math.ceil(width) + 1;
|
|
1013
|
+
const layer = this.__shape_layer__(margin);
|
|
1014
|
+
const coverage = new Uint8Array(layer.width * layer.height);
|
|
1015
|
+
for (let i = 0; i < coverage.length; i++)
|
|
1016
|
+
coverage[i] = layer.bitmap[i * 4 + 3];
|
|
1017
|
+
const stroke = outline(coverage, layer.width, layer.height, width);
|
|
1018
|
+
const bitmap = layer.bitmap;
|
|
1019
|
+
for (let i = 0; i < coverage.length; i++) {
|
|
1020
|
+
bitmap[i * 4] = r;
|
|
1021
|
+
bitmap[i * 4 + 1] = g;
|
|
1022
|
+
bitmap[i * 4 + 2] = b;
|
|
1023
|
+
bitmap[i * 4 + 3] = stroke[i] * (1 - coverage[i] / 255) * a;
|
|
1024
|
+
}
|
|
1025
|
+
const room = this.__room__(), grow = Math.ceil(width);
|
|
1026
|
+
return this.__under__(layer, -margin, -margin, expand
|
|
1027
|
+
? { left: Math.min(room.left, grow), top: Math.min(room.top, grow), right: grow, bottom: grow }
|
|
1028
|
+
: { left: 0, top: 0, right: 0, bottom: 0 });
|
|
1029
|
+
}
|
|
1030
|
+
__shape_layer__(margin) {
|
|
1031
|
+
const layer = new Image(this.width + 2 * margin, this.height + 2 * margin);
|
|
1032
|
+
for (let y = 0; y < this.height; y++)
|
|
1033
|
+
for (let x = 0; x < this.width; x++)
|
|
1034
|
+
layer.bitmap[((y + margin) * layer.width + x + margin) * 4 + 3] = this.bitmap[(y * this.width + x) * 4 + 3];
|
|
1035
|
+
return layer;
|
|
1036
|
+
}
|
|
1037
|
+
__under__(layer, layerX, layerY, grow) {
|
|
1038
|
+
const { left, top, right, bottom } = grow;
|
|
1039
|
+
const width = this.width + left + right, height = this.height + top + bottom;
|
|
1040
|
+
const result = new Image(width, height);
|
|
1041
|
+
result.composite(layer, { x: layerX + left, y: layerY + top });
|
|
1042
|
+
const map = this.__gain_map__;
|
|
1043
|
+
this.__gain_map__ = null;
|
|
1044
|
+
try {
|
|
1045
|
+
result.composite(this, { x: left, y: top });
|
|
1046
|
+
}
|
|
1047
|
+
finally {
|
|
1048
|
+
this.__gain_map__ = map;
|
|
1049
|
+
}
|
|
1050
|
+
map?.__transform__(this.width, this.height, width, height, (X, Y) => [X - left, Y - top]);
|
|
1051
|
+
this.__apply__(result);
|
|
1052
|
+
if (left || top)
|
|
1053
|
+
this.__grown__(left, top);
|
|
1054
|
+
return this;
|
|
1055
|
+
}
|
|
1056
|
+
__room__() {
|
|
1057
|
+
return { left: Infinity, top: Infinity };
|
|
1058
|
+
}
|
|
1059
|
+
__grown__(_left, _top) {
|
|
1060
|
+
}
|
|
796
1061
|
sharpen(amountOrOptions = 1, radiusArgument = 1) {
|
|
797
1062
|
const { amount = 1, radius = 1 } = isOptions(amountOrOptions) ? amountOrOptions : { amount: amountOrOptions, radius: radiusArgument };
|
|
798
1063
|
if (!Number.isFinite(amount) || amount < 0)
|
|
@@ -1341,7 +1606,7 @@ export class Image {
|
|
|
1341
1606
|
static SVG_MODE_WIDTH = 2;
|
|
1342
1607
|
static SVG_MODE_HEIGHT = 3;
|
|
1343
1608
|
static async renderSVG(svg, sizeOrOptions = 1, modeArgument = SVGScaleModes.SCALE) {
|
|
1344
|
-
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 };
|
|
1345
1610
|
const mode = LEGACY_SVG_MODES.get(givenMode) ?? givenMode;
|
|
1346
1611
|
if (mode !== 'scale' && mode !== 'width' && mode !== 'height')
|
|
1347
1612
|
throw new Error('Invalid SVG scaling mode');
|
|
@@ -1350,18 +1615,31 @@ export class Image {
|
|
|
1350
1615
|
throw new RangeError('SVG scale must be > 0');
|
|
1351
1616
|
if (mode !== SVGScaleModes.SCALE && size < 1)
|
|
1352
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
|
+
}
|
|
1353
1627
|
const source = typeof svg === 'string' ? svg : view(svg);
|
|
1354
1628
|
const images = new Map();
|
|
1355
|
-
for (const { href, data } of svgRenderer.
|
|
1356
|
-
|
|
1629
|
+
for (const { href, data } of svgRenderer.imageReferences(source)) {
|
|
1630
|
+
const value = given.get(href) ?? data;
|
|
1631
|
+
if (!value)
|
|
1357
1632
|
continue;
|
|
1358
1633
|
try {
|
|
1359
|
-
if (
|
|
1360
|
-
|
|
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);
|
|
1361
1639
|
images.set(href, { width: decoded.width, height: decoded.height, pixels: gif.composite(decoded)[0].pixels });
|
|
1362
1640
|
}
|
|
1363
1641
|
else {
|
|
1364
|
-
const image = await Image.decode(
|
|
1642
|
+
const image = await Image.decode(value);
|
|
1365
1643
|
images.set(href, { width: image.width, height: image.height, pixels: image.bitmap });
|
|
1366
1644
|
}
|
|
1367
1645
|
}
|
|
@@ -1512,6 +1790,14 @@ const BLEND_MODES = {
|
|
|
1512
1790
|
'exclusion': (b, s) => b + s - 2 * b * s,
|
|
1513
1791
|
'add': (b, s) => Math.min(1, b + s)
|
|
1514
1792
|
};
|
|
1793
|
+
function gradientFunction(stops) {
|
|
1794
|
+
if (!Array.isArray(stops))
|
|
1795
|
+
return Colors.gradient(stops);
|
|
1796
|
+
if (!stops.length)
|
|
1797
|
+
throw new RangeError('Invalid gradient point count');
|
|
1798
|
+
const colors = stops.length === 1 ? [stops[0], stops[0]] : stops;
|
|
1799
|
+
return Colors.gradient(Object.fromEntries(colors.map((color, i) => [i / (colors.length - 1), color])));
|
|
1800
|
+
}
|
|
1515
1801
|
const OUTLINE_WINDOW = 1;
|
|
1516
1802
|
function outline(coverage, width, height, radius) {
|
|
1517
1803
|
const count = width * height;
|
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, 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';
|
package/dist/render/colr.js
CHANGED
|
@@ -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;
|
package/dist/render/svg-text.js
CHANGED
|
@@ -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) {
|
package/dist/render/svg.js
CHANGED
|
@@ -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
|
|
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
|
|
181
|
-
|
|
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.
|
|
1
|
+
export const VERSION = '3.20.0';
|