@jimp/wasm-svg 0.0.0-stage → 2.1.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/LICENSE +21 -0
- package/README.md +146 -2
- package/RESVG-LICENSE +373 -0
- package/dist/browser/detect.d.ts +7 -0
- package/dist/browser/detect.d.ts.map +1 -0
- package/dist/browser/detect.js +56 -0
- package/dist/browser/detect.js.map +1 -0
- package/dist/browser/index.d.ts +43 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/browser/index.js +211 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/load-wasm-browser.d.mts.map +1 -0
- package/dist/browser/load-wasm-browser.mjs.map +1 -0
- package/dist/browser/load-wasm.d.ts +6 -0
- package/dist/browser/load-wasm.js +17 -0
- package/dist/browser/package.json +3 -0
- package/dist/browser/resvg.wasm +0 -0
- package/dist/esm/detect.d.ts +7 -0
- package/dist/esm/detect.d.ts.map +1 -0
- package/dist/esm/detect.js +56 -0
- package/dist/esm/detect.js.map +1 -0
- package/dist/esm/index.d.ts +43 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +211 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/load-wasm.d.ts +3 -0
- package/dist/esm/load-wasm.d.ts.map +1 -0
- package/dist/esm/load-wasm.js +9 -0
- package/dist/esm/load-wasm.js.map +1 -0
- package/dist/esm/package.json +3 -0
- package/package.json +78 -4
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { Buffer } from "buffer";
|
|
2
|
+
import { initWasm, Resvg } from "@resvg/resvg-wasm";
|
|
3
|
+
import { cssColorToHex } from "@jimp/utils";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { isSvg } from "./detect.js";
|
|
6
|
+
import { loadWasm } from "./load-wasm.js";
|
|
7
|
+
const DecodeSvgOptionsSchema = z
|
|
8
|
+
.object({
|
|
9
|
+
/**
|
|
10
|
+
* Width to render at, in pixels. The height keeps the SVG's aspect ratio.
|
|
11
|
+
* With `height` too, the image fits inside both.
|
|
12
|
+
* Defaults to the SVG's own size.
|
|
13
|
+
*/
|
|
14
|
+
width: z.number().positive().optional(),
|
|
15
|
+
/**
|
|
16
|
+
* Height to render at, in pixels. The width keeps the SVG's aspect ratio.
|
|
17
|
+
* With `width` too, the image fits inside both.
|
|
18
|
+
* Defaults to the SVG's own size.
|
|
19
|
+
*/
|
|
20
|
+
height: z.number().positive().optional(),
|
|
21
|
+
/**
|
|
22
|
+
* Render at a multiple of the SVG's own size, e.g. 2 for twice the
|
|
23
|
+
* width and height. Can't be combined with `width` or `height`.
|
|
24
|
+
* @default 1
|
|
25
|
+
*/
|
|
26
|
+
scale: z.number().positive().optional(),
|
|
27
|
+
/**
|
|
28
|
+
* Fill the image with this colour behind the SVG: a CSS colour or a
|
|
29
|
+
* 0xRRGGBBAA number.
|
|
30
|
+
* @default transparent
|
|
31
|
+
*/
|
|
32
|
+
background: z.union([z.string(), z.number()]).optional(),
|
|
33
|
+
/**
|
|
34
|
+
* Fonts (TTF, OTF, TTC or WOFF2) to draw `<text>` with. Without any, text isn't
|
|
35
|
+
* drawn: the plugin has no access to system fonts.
|
|
36
|
+
*/
|
|
37
|
+
fonts: z.array(z.instanceof(Uint8Array)).optional(),
|
|
38
|
+
/**
|
|
39
|
+
* The family to use for text that doesn't set `font-family`, and for the
|
|
40
|
+
* generic `serif`, `sans-serif` and `monospace` families. Text in a family
|
|
41
|
+
* none of the `fonts` have falls back to a font that has its characters.
|
|
42
|
+
*/
|
|
43
|
+
defaultFontFamily: z.string().optional(),
|
|
44
|
+
/**
|
|
45
|
+
* Largest image, in megapixels, that will be rendered. Larger sizes are
|
|
46
|
+
* rejected before any pixel memory is allocated.
|
|
47
|
+
* @default 100
|
|
48
|
+
*/
|
|
49
|
+
maxResolutionInMP: z.number().positive().optional(),
|
|
50
|
+
/**
|
|
51
|
+
* Loads the http(s) URLs of `<image>` elements, which are otherwise
|
|
52
|
+
* skipped, by returning the PNG, JPEG or GIF's bytes. Images in `data:`
|
|
53
|
+
* URLs are always drawn.
|
|
54
|
+
*
|
|
55
|
+
* Only use this for SVGs you trust, or check the URL first: an untrusted
|
|
56
|
+
* SVG can make your server request any URL, including internal ones.
|
|
57
|
+
*/
|
|
58
|
+
resolveImage: z
|
|
59
|
+
.custom((value) => typeof value === "function")
|
|
60
|
+
.optional(),
|
|
61
|
+
})
|
|
62
|
+
.strict()
|
|
63
|
+
.refine(({ scale, width, height }) => scale === undefined || (width === undefined && height === undefined), "Pass either scale or width and height, not both");
|
|
64
|
+
let resvgReady;
|
|
65
|
+
function initResvgOnce(module) {
|
|
66
|
+
resvgReady ??= Promise.resolve(module ?? loadWasm())
|
|
67
|
+
.then((wasm) => initWasm(wasm))
|
|
68
|
+
.catch((error) => {
|
|
69
|
+
// Another copy of the plugin, or the app, has initialized it already
|
|
70
|
+
if (!(error instanceof Error && error.message.startsWith("Already"))) {
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
return resvgReady;
|
|
75
|
+
}
|
|
76
|
+
/** resvg renders premultiplied RGBA, which Jimp doesn't use */
|
|
77
|
+
function unpremultiply(pixels) {
|
|
78
|
+
// Already copied out of wasm memory, so it's converted in place
|
|
79
|
+
const data = Buffer.from(pixels.buffer, pixels.byteOffset, pixels.byteLength);
|
|
80
|
+
for (let i = 0; i < data.length; i += 4) {
|
|
81
|
+
const alpha = data[i + 3];
|
|
82
|
+
if (alpha !== 0 && alpha !== 255) {
|
|
83
|
+
for (let c = i; c < i + 3; c++) {
|
|
84
|
+
data[c] = Math.min(255, Math.round((data[c] * 255) / alpha));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return data;
|
|
89
|
+
}
|
|
90
|
+
function toHexColor(color) {
|
|
91
|
+
return `#${(cssColorToHex(color) >>> 0).toString(16).padStart(8, "0")}`;
|
|
92
|
+
}
|
|
93
|
+
/** How resvg should scale the SVG, when that doesn't depend on its size */
|
|
94
|
+
function getFit({ width, height, scale, }) {
|
|
95
|
+
if (width !== undefined && height !== undefined) {
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
if (width !== undefined) {
|
|
99
|
+
return { mode: "width", value: Math.max(1, Math.round(width)) };
|
|
100
|
+
}
|
|
101
|
+
if (height !== undefined) {
|
|
102
|
+
return { mode: "height", value: Math.max(1, Math.round(height)) };
|
|
103
|
+
}
|
|
104
|
+
return scale === undefined
|
|
105
|
+
? { mode: "original" }
|
|
106
|
+
: { mode: "zoom", value: scale };
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The size to render the SVG at, rounded like resvg does, and how resvg
|
|
110
|
+
* should scale the SVG's own size to it
|
|
111
|
+
*/
|
|
112
|
+
function getRenderSize(intrinsicWidth, intrinsicHeight, options) {
|
|
113
|
+
let { width, height } = options;
|
|
114
|
+
// Fit inside both, so whichever is smaller relative to the SVG wins
|
|
115
|
+
if (width !== undefined && height !== undefined) {
|
|
116
|
+
if (width / intrinsicWidth <= height / intrinsicHeight) {
|
|
117
|
+
height = undefined;
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
width = undefined;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const fitTo = getFit({ ...options, width, height });
|
|
124
|
+
switch (fitTo.mode) {
|
|
125
|
+
case "width":
|
|
126
|
+
return {
|
|
127
|
+
fitTo,
|
|
128
|
+
width: fitTo.value,
|
|
129
|
+
height: Math.round((fitTo.value * intrinsicHeight) / intrinsicWidth),
|
|
130
|
+
};
|
|
131
|
+
case "height":
|
|
132
|
+
return {
|
|
133
|
+
fitTo,
|
|
134
|
+
width: Math.round((fitTo.value * intrinsicWidth) / intrinsicHeight),
|
|
135
|
+
height: fitTo.value,
|
|
136
|
+
};
|
|
137
|
+
case "original":
|
|
138
|
+
return { fitTo, width: intrinsicWidth, height: intrinsicHeight };
|
|
139
|
+
case "zoom": {
|
|
140
|
+
// At least a pixel across the smaller side
|
|
141
|
+
const value = Math.max(fitTo.value, 1 / Math.min(intrinsicWidth, intrinsicHeight));
|
|
142
|
+
return {
|
|
143
|
+
fitTo: { mode: "zoom", value },
|
|
144
|
+
width: Math.round(intrinsicWidth * value),
|
|
145
|
+
height: Math.round(intrinsicHeight * value),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
async function decode(data, options, wasm) {
|
|
151
|
+
const { background, fonts = [], defaultFontFamily, maxResolutionInMP = 100, resolveImage, ...size } = DecodeSvgOptionsSchema.parse(options);
|
|
152
|
+
const renderOptions = {
|
|
153
|
+
background: background === undefined ? undefined : toHexColor(background),
|
|
154
|
+
// Only the given fonts: the wasm has no access to the system's
|
|
155
|
+
font: { fontBuffers: fonts, defaultFontFamily },
|
|
156
|
+
};
|
|
157
|
+
const fitTo = getFit(size);
|
|
158
|
+
await initResvgOnce(wasm);
|
|
159
|
+
// Parses the SVG. The pixels are only allocated by render()
|
|
160
|
+
let svg = new Resvg(data, { ...renderOptions, fitTo });
|
|
161
|
+
try {
|
|
162
|
+
const target = getRenderSize(svg.width, svg.height, size);
|
|
163
|
+
if (target.width * target.height > maxResolutionInMP * 1_000_000) {
|
|
164
|
+
throw new Error(`SVG dimensions ${target.width}x${target.height} exceed the maximum resolution of ${maxResolutionInMP} megapixels. Use the width, height or scale option to render it smaller.`);
|
|
165
|
+
}
|
|
166
|
+
// The scale depends on the SVG's size, and is a parsing option
|
|
167
|
+
if (JSON.stringify(target.fitTo) !== JSON.stringify(fitTo)) {
|
|
168
|
+
const scaled = new Resvg(data, { ...renderOptions, fitTo: target.fitTo });
|
|
169
|
+
svg.free();
|
|
170
|
+
svg = scaled;
|
|
171
|
+
}
|
|
172
|
+
if (resolveImage) {
|
|
173
|
+
for (const href of svg.imagesToResolve()) {
|
|
174
|
+
const image = await resolveImage(href);
|
|
175
|
+
if (image) {
|
|
176
|
+
svg.resolveImage(href, image);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const image = svg.render();
|
|
181
|
+
try {
|
|
182
|
+
return {
|
|
183
|
+
data: unpremultiply(image.pixels),
|
|
184
|
+
width: image.width,
|
|
185
|
+
height: image.height,
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
image.free();
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
finally {
|
|
193
|
+
svg.free();
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* SVG images (.svg), rendered with resvg. Only reading is supported: writing
|
|
198
|
+
* would need a raster to vector conversion.
|
|
199
|
+
*/
|
|
200
|
+
export default function svg({ wasm } = {}) {
|
|
201
|
+
return {
|
|
202
|
+
mime: "image/svg+xml",
|
|
203
|
+
hasAlpha: true,
|
|
204
|
+
detect: isSvg,
|
|
205
|
+
encode: async () => {
|
|
206
|
+
throw new Error("Jimp can read SVG but can't write it. Write a raster format like PNG (image/png) instead.");
|
|
207
|
+
},
|
|
208
|
+
decode: (data, options = {}) => decode(data, options, wasm?.resvg),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAsB,MAAM,mBAAmB,CAAC;AAExE,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAO1C,MAAM,sBAAsB,GAAG,CAAC;KAC7B,MAAM,CAAC;IACN;;;;OAIG;IACH,KAAK,EAAE,CA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AM,YAAY,CAAC,IAAI,CAAC,CAAC;gBAEvC,IAAI,KAAK,EAAE,CAAC;oBACV,GAAG,CAAC,YAAY,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;gBAChC,CAAC;YACH,CAAC;QACH,CAAC;QAED,MAAM,KAAK,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC;QAE3B,IAAI,CAAC;YACH,OAAO;gBACL,IAAI,EAAE,aAAa,CAAC,KAAK,CAAC,MAAM,CAAC;gBACjC,KAAK,EAAE,KAAK,CAAC,KAAK;gBAClB,MAAM,EAAE,KAAK,CAAC,MAAM;aACrB,CAAC;QACJ,CAAC;gBAAS,CAAC;YACT,KAAK,CAAC,IAAI,EAAE,CAAC;QACf,CAAC;IACH,CAAC;YAAS,CAAC;QACT,GAAG,CAAC,IAAI,EAAE,CAAC;IACb,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,OAAO,UAAU,GAAG,CAAC,EAAE,IAAI,EAAE,GAAqB,EAAE;IACzD,OAAO;QACL,IAAI,EAAE,eAAe;QACrB,QAAQ,EAAE,IAAI;QACd,MAAM,EAAE,KAAK;QACb,MAAM,EAAE,KAAK,IAAI,EAAE;YACjB,MAAM,IAAI,KAAK,CACb,2FAA2F,CAC5F,CAAC;QACJ,CAAC;QACD,MAAM,EAAE,CAAC,IAAI,EAAE,OAAO,GAAqB,EAAE,EAAE,EAAE,CAC/C,MAAM,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC;KACH,CAAC;AACtC,CAAC","sourcesContent":["import { Buffer } from \"buffer\";\nimport { initWasm, Resvg, ResvgRenderOptions } from \"@resvg/resvg-wasm\";\nimport { Bitmap, Format } from \"@jimp/types\";\nimport { cssColorToHex } from \"@jimp/utils\";\nimport { z } from \"zod\";\n\nimport { isSvg } from \"./detect.js\";\nimport { loadWasm } from \"./load-wasm.js\";\n\n/** Returns the bytes of an image an SVG links to, or nothing to skip it */\nexport type ResolveImage = (\n href: string,\n) => Uint8Array | undefined | Promise<Uint8Array | undefined>;\n\nconst DecodeSvgOptionsSchema = z\n .object({\n /**\n * Width to render at, in pixels. The height keeps the SVG's aspect ratio.\n * With `height` too, the image fits inside both.\n * Defaults to the SVG's own size.\n */\n width: z.number().positive().optional(),\n /**\n * Height to render at, in pixels. The width keeps the SVG's aspect ratio.\n * With `width` too, the image fits inside both.\n * Defaults to the SVG's own size.\n */\n height: z.number().positive().optional(),\n /**\n * Render at a multiple of the SVG's own size, e.g. 2 for twice the\n * width and height. Can't be combined with `width` or `height`.\n * @default 1\n */\n scale: z.number().positive().optional(),\n /**\n * Fill the image with this colour behind the SVG: a CSS colour or a\n * 0xRRGGBBAA number.\n * @default transparent\n */\n background: z.union([z.string(), z.number()]).optional(),\n /**\n * Fonts (TTF, OTF, TTC or WOFF2) to draw `<text>` with. Without any, text isn't\n * drawn: the plugin has no access to system fonts.\n */\n fonts: z.array(z.instanceof(Uint8Array)).optional(),\n /**\n * The family to use for text that doesn't set `font-family`, and for the\n * generic `serif`, `sans-serif` and `monospace` families. Text in a family\n * none of the `fonts` have falls back to a font that has its characters.\n */\n defaultFontFamily: z.string().optional(),\n /**\n * Largest image, in megapixels, that will be rendered. Larger sizes are\n * rejected before any pixel memory is allocated.\n * @default 100\n */\n maxResolutionInMP: z.number().positive().optional(),\n /**\n * Loads the http(s) URLs of `<image>` elements, which are otherwise\n * skipped, by returning the PNG, JPEG or GIF's bytes. Images in `data:`\n * URLs are always drawn.\n *\n * Only use this for SVGs you trust, or check the URL first: an untrusted\n * SVG can make your server request any URL, including internal ones.\n */\n resolveImage: z\n .custom<ResolveImage>((value) => typeof value === \"function\")\n .optional(),\n })\n .strict()\n .refine(\n ({ scale, width, height }) =>\n scale === undefined || (width === undefined && height === undefined),\n \"Pass either scale or width and height, not both\",\n );\n\nexport type DecodeSvgOptions = z.input<typeof DecodeSvgOptionsSchema>;\n\nexport interface SvgWasm {\n /** The compiled `@resvg/resvg-wasm/index_bg.wasm` */\n resvg?: WebAssembly.Module;\n}\n\nexport interface SvgFormatOptions {\n /**\n * A precompiled wasm module for runtimes or bundlers where the plugin\n * can't load resvg's wasm itself.\n * resvg is initialized once, by the first instance that decodes, so pass\n * the same module to every instance.\n */\n wasm?: SvgWasm;\n}\n\nlet resvgReady: Promise<void> | undefined;\n\nfunction initResvgOnce(module?: WebAssembly.Module) {\n resvgReady ??= Promise.resolve(module ?? loadWasm())\n .then((wasm) => initWasm(wasm))\n .catch((error: unknown) => {\n // Another copy of the plugin, or the app, has initialized it already\n if (!(error instanceof Error && error.message.startsWith(\"Already\"))) {\n throw error;\n }\n });\n return resvgReady;\n}\n\n/** resvg renders premultiplied RGBA, which Jimp doesn't use */\nfunction unpremultiply(pixels: Uint8Array) {\n // Already copied out of wasm memory, so it's converted in place\n const data = Buffer.from(pixels.buffer, pixels.byteOffset, pixels.byteLength);\n\n for (let i = 0; i < data.length; i += 4) {\n const alpha = data[i + 3]!;\n\n if (alpha !== 0 && alpha !== 255) {\n for (let c = i; c < i + 3; c++) {\n data[c] = Math.min(255, Math.round((data[c]! * 255) / alpha));\n }\n }\n }\n\n return data;\n}\n\nfunction toHexColor(color: string | number) {\n return `#${(cssColorToHex(color) >>> 0).toString(16).padStart(8, \"0\")}`;\n}\n\n/** How resvg should scale the SVG, when that doesn't depend on its size */\nfunction getFit({\n width,\n height,\n scale,\n}: DecodeSvgOptions): ResvgRenderOptions[\"fitTo\"] {\n if (width !== undefined && height !== undefined) {\n return undefined;\n }\n\n if (width !== undefined) {\n return { mode: \"width\", value: Math.max(1, Math.round(width)) };\n }\n\n if (height !== undefined) {\n return { mode: \"height\", value: Math.max(1, Math.round(height)) };\n }\n\n return scale === undefined\n ? { mode: \"original\" }\n : { mode: \"zoom\", value: scale };\n}\n\n/**\n * The size to render the SVG at, rounded like resvg does, and how resvg\n * should scale the SVG's own size to it\n */\nfunction getRenderSize(\n intrinsicWidth: number,\n intrinsicHeight: number,\n options: DecodeSvgOptions,\n) {\n let { width, height } = options;\n\n // Fit inside both, so whichever is smaller relative to the SVG wins\n if (width !== undefined && height !== undefined) {\n if (width / intrinsicWidth <= height / intrinsicHeight) {\n height = undefined;\n } else {\n width = undefined;\n }\n }\n\n const fitTo = getFit({ ...options, width, height })!;\n\n switch (fitTo.mode) {\n case \"width\":\n return {\n fitTo,\n width: fitTo.value,\n height: Math.round((fitTo.value * intrinsicHeight) / intrinsicWidth),\n };\n case \"height\":\n return {\n fitTo,\n width: Math.round((fitTo.value * intrinsicWidth) / intrinsicHeight),\n height: fitTo.value,\n };\n case \"original\":\n return { fitTo, width: intrinsicWidth, height: intrinsicHeight };\n case \"zoom\": {\n // At least a pixel across the smaller side\n const value = Math.max(\n fitTo.value,\n 1 / Math.min(intrinsicWidth, intrinsicHeight),\n );\n\n return {\n fitTo: { mode: \"zoom\", value } as const,\n width: Math.round(intrinsicWidth * value),\n height: Math.round(intrinsicHeight * value),\n };\n }\n }\n}\n\nasync function decode(\n data: Buffer,\n options: DecodeSvgOptions,\n wasm?: WebAssembly.Module,\n): Promise<Bitmap> {\n const {\n background,\n fonts = [],\n defaultFontFamily,\n maxResolutionInMP = 100,\n resolveImage,\n ...size\n } = DecodeSvgOptionsSchema.parse(options);\n const renderOptions: ResvgRenderOptions = {\n background: background === undefined ? undefined : toHexColor(background),\n // Only the given fonts: the wasm has no access to the system's\n font: { fontBuffers: fonts, defaultFontFamily },\n };\n const fitTo = getFit(size);\n\n await initResvgOnce(wasm);\n\n // Parses the SVG. The pixels are only allocated by render()\n let svg = new Resvg(data, { ...renderOptions, fitTo });\n\n try {\n const target = getRenderSize(svg.width, svg.height, size);\n\n if (target.width * target.height > maxResolutionInMP * 1_000_000) {\n throw new Error(\n `SVG dimensions ${target.width}x${target.height} exceed the maximum resolution of ${maxResolutionInMP} megapixels. Use the width, height or scale option to render it smaller.`,\n );\n }\n\n // The scale depends on the SVG's size, and is a parsing option\n if (JSON.stringify(target.fitTo) !== JSON.stringify(fitTo)) {\n const scaled = new Resvg(data, { ...renderOptions, fitTo: target.fitTo });\n svg.free();\n svg = scaled;\n }\n\n if (resolveImage) {\n for (const href of svg.imagesToResolve() as string[]) {\n const image = await resolveImage(href);\n\n if (image) {\n svg.resolveImage(href, image);\n }\n }\n }\n\n const image = svg.render();\n\n try {\n return {\n data: unpremultiply(image.pixels),\n width: image.width,\n height: image.height,\n };\n } finally {\n image.free();\n }\n } finally {\n svg.free();\n }\n}\n\n/**\n * SVG images (.svg), rendered with resvg. Only reading is supported: writing\n * would need a raster to vector conversion.\n */\nexport default function svg({ wasm }: SvgFormatOptions = {}) {\n return {\n mime: \"image/svg+xml\",\n hasAlpha: true,\n detect: isSvg,\n encode: async () => {\n throw new Error(\n \"Jimp can read SVG but can't write it. Write a raster format like PNG (image/png) instead.\",\n );\n },\n decode: (data, options: DecodeSvgOptions = {}) =>\n decode(data, options, wasm?.resvg),\n } satisfies Format<\"image/svg+xml\">;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-wasm-browser.d.mts","sourceRoot":"","sources":["../../src/load-wasm-browser.mts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,wBAAsB,QAAQ,gCAa7B"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-wasm-browser.mjs","sourceRoot":"","sources":["../../src/load-wasm-browser.mts"],"names":[],"mappings":"AAAA,2CAA2C;AAC3C,MAAM,UAAU,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAE5C;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ;IAC5B,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,cAAc,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;IACrD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,CAAC;IAClC,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,MAAM,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;IAE1D,qDAAqD;IACrD,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,EAAE,CAAC;QACnE,MAAM,IAAI,KAAK,CACb,oCAAoC,GAAG,6KAA6K,CACrN,CAAC;IACJ,CAAC;IAED,OAAO,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AACnC,CAAC","sourcesContent":["/** The first bytes of every wasm module */\nconst WASM_MAGIC = [0x00, 0x61, 0x73, 0x6d];\n\n/**\n * The build copies resvg's wasm next to this file. Bundlers like Vite,\n * webpack 5 and Rollup emit it as an asset from the `new URL`.\n */\nexport async function loadWasm() {\n const url = new URL(\"./resvg.wasm\", import.meta.url);\n const response = await fetch(url);\n const wasm = new Uint8Array(await response.arrayBuffer());\n\n // A dev server can answer with its HTML page instead\n if (!response.ok || WASM_MAGIC.some((byte, i) => wasm[i] !== byte)) {\n throw new Error(\n `Failed to load resvg's wasm from ${url}. If your bundler moves @jimp/wasm-svg away from it, like Vite 7's dependency pre-bundling, see the package's README, or pass the compiled module as the wasm.resvg option.`,\n );\n }\n\n return WebAssembly.compile(wasm);\n}\n"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** The first bytes of every wasm module */
|
|
2
|
+
const WASM_MAGIC = [0x00, 0x61, 0x73, 0x6d];
|
|
3
|
+
/**
|
|
4
|
+
* The build copies resvg's wasm next to this file. Bundlers like Vite,
|
|
5
|
+
* webpack 5 and Rollup emit it as an asset from the `new URL`.
|
|
6
|
+
*/
|
|
7
|
+
export async function loadWasm() {
|
|
8
|
+
const url = new URL("./resvg.wasm", import.meta.url);
|
|
9
|
+
const response = await fetch(url);
|
|
10
|
+
const wasm = new Uint8Array(await response.arrayBuffer());
|
|
11
|
+
// A dev server can answer with its HTML page instead
|
|
12
|
+
if (!response.ok || WASM_MAGIC.some((byte, i) => wasm[i] !== byte)) {
|
|
13
|
+
throw new Error(`Failed to load resvg's wasm from ${url}. If your bundler moves @jimp/wasm-svg away from it, like Vite 7's dependency pre-bundling, see the package's README, or pass the compiled module as the wasm.resvg option.`);
|
|
14
|
+
}
|
|
15
|
+
return WebAssembly.compile(wasm);
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=load-wasm-browser.mjs.map
|
|
Binary file
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether the data starts like an SVG document: an optional UTF-8 BOM, then
|
|
3
|
+
* any XML declaration, processing instructions, comments and doctype before
|
|
4
|
+
* an `<svg>` root element. It only looks at the start, and doesn't parse it.
|
|
5
|
+
*/
|
|
6
|
+
export declare function isSvg(data: Uint8Array): boolean;
|
|
7
|
+
//# sourceMappingURL=detect.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"detect.d.ts","sourceRoot":"","sources":["../../src/detect.ts"],"names":[],"mappings":"AAoBA;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,IAAI,EAAE,UAAU,WAqCrC"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How much of the data to look at. The root element comes after the XML
|
|
3
|
+
* declaration, comments and a doctype, which editors like Illustrator fill
|
|
4
|
+
* with entities, but not much further in.
|
|
5
|
+
*/
|
|
6
|
+
const SNIFF_LENGTH = 16 * 1024;
|
|
7
|
+
/** `<svg` or a prefixed `<svg:svg`, then whitespace, `>` or `/` */
|
|
8
|
+
const SVG_ROOT = /^<(?:[A-Za-z_][\w.-]*:)?svg[\s/>]/;
|
|
9
|
+
function isWhitespace(char) {
|
|
10
|
+
return char === " " || char === "\t" || char === "\n" || char === "\r";
|
|
11
|
+
}
|
|
12
|
+
/** The index after the first `token` from `from`, or -1 when there's none */
|
|
13
|
+
function after(text, token, from) {
|
|
14
|
+
const index = text.indexOf(token, from);
|
|
15
|
+
return index === -1 ? -1 : index + token.length;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Whether the data starts like an SVG document: an optional UTF-8 BOM, then
|
|
19
|
+
* any XML declaration, processing instructions, comments and doctype before
|
|
20
|
+
* an `<svg>` root element. It only looks at the start, and doesn't parse it.
|
|
21
|
+
*/
|
|
22
|
+
export function isSvg(data) {
|
|
23
|
+
// Maps each byte to a character, so the markup can be found without
|
|
24
|
+
// decoding UTF-8
|
|
25
|
+
const text = new TextDecoder("latin1").decode(data.subarray(0, SNIFF_LENGTH));
|
|
26
|
+
let i = text.startsWith("\xef\xbb\xbf") ? 3 : 0;
|
|
27
|
+
while (i < text.length) {
|
|
28
|
+
while (isWhitespace(text[i])) {
|
|
29
|
+
i++;
|
|
30
|
+
}
|
|
31
|
+
let end;
|
|
32
|
+
if (text.startsWith("<?", i)) {
|
|
33
|
+
end = after(text, "?>", i + 2);
|
|
34
|
+
}
|
|
35
|
+
else if (text.startsWith("<!--", i)) {
|
|
36
|
+
end = after(text, "-->", i + 4);
|
|
37
|
+
}
|
|
38
|
+
else if (text.startsWith("<!DOCTYPE", i)) {
|
|
39
|
+
const subset = text.indexOf("[", i);
|
|
40
|
+
const close = text.indexOf(">", i);
|
|
41
|
+
// An internal subset's declarations contain `>` too
|
|
42
|
+
const from = subset !== -1 && subset < close ? after(text, "]", subset) : i;
|
|
43
|
+
end = from === -1 ? -1 : after(text, ">", from);
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
return SVG_ROOT.test(text.slice(i, i + 64));
|
|
47
|
+
}
|
|
48
|
+
// Cut off before the end of the markup
|
|
49
|
+
if (end === -1) {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
i = end;
|
|
53
|
+
}
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=detect.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"detect.js","sourceRoot":"","sources":["../../src/detect.ts"],"names":[],"mappings":"AAAA;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AAI,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC;YACtC,GAAG,GAAG,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;QAClC,CAAC;aAAM,IAAI,IAAI,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,CAAC,EAAE,CAAC;YAC3C,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;YACpC,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;YACnC,oDAAoD;YACpD,MAAM,IAAI,GACR,MAAM,KAAK,CAAC,CAAC,IAAI,MAAM,GAAG,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YACjE,GAAG,GAAG,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;QAClD,CAAC;aAAM,CAAC;YACN,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QAC9C,CAAC;QAED,uCAAuC;QACvC,IAAI,GAAG,KAAK,CAAC,CAAC,EAAE,CAAC;YACf,OAAO,KAAK,CAAC;QACf,CAAC;QAED,CAAC,GAAG,GAAG,CAAC;IACV,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/**\n * How much of the data to look at. The root element comes after the XML\n * declaration, comments and a doctype, which editors like Illustrator fill\n * with entities, but not much further in.\n */\nconst SNIFF_LENGTH = 16 * 1024;\n\n/** `<svg` or a prefixed `<svg:svg`, then whitespace, `>` or `/` */\nconst SVG_ROOT = /^<(?:[A-Za-z_][\\w.-]*:)?svg[\\s/>]/;\n\nfunction isWhitespace(char: string | undefined) {\n return char === \" \" || char === \"\\t\" || char === \"\\n\" || char === \"\\r\";\n}\n\n/** The index after the first `token` from `from`, or -1 when there's none */\nfunction after(text: string, token: string, from: number) {\n const index = text.indexOf(token, from);\n return index === -1 ? -1 : index + token.length;\n}\n\n/**\n * Whether the data starts like an SVG document: an optional UTF-8 BOM, then\n * any XML declaration, processing instructions, comments and doctype before\n * an `<svg>` root element. It only looks at the start, and doesn't parse it.\n */\nexport function isSvg(data: Uint8Array) {\n // Maps each byte to a character, so the markup can be found without\n // decoding UTF-8\n const text = new TextDecoder(\"latin1\").decode(data.subarray(0, SNIFF_LENGTH));\n let i = text.startsWith(\"\\xef\\xbb\\xbf\") ? 3 : 0;\n\n while (i < text.length) {\n while (isWhitespace(text[i])) {\n i++;\n }\n\n let end: number;\n\n if (text.startsWith(\"<?\", i)) {\n end = after(text, \"?>\", i + 2);\n } else if (text.startsWith(\"<!--\", i)) {\n end = after(text, \"-->\", i + 4);\n } else if (text.startsWith(\"<!DOCTYPE\", i)) {\n const subset = text.indexOf(\"[\", i);\n const close = text.indexOf(\">\", i);\n // An internal subset's declarations contain `>` too\n const from =\n subset !== -1 && subset < close ? after(text, \"]\", subset) : i;\n end = from === -1 ? -1 : after(text, \">\", from);\n } else {\n return SVG_ROOT.test(text.slice(i, i + 64));\n }\n\n // Cut off before the end of the markup\n if (end === -1) {\n return false;\n }\n\n i = end;\n }\n\n return false;\n}\n"]}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Buffer } from "buffer";
|
|
2
|
+
import { Bitmap } from "@jimp/types";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { isSvg } from "./detect.js";
|
|
5
|
+
/** Returns the bytes of an image an SVG links to, or nothing to skip it */
|
|
6
|
+
export type ResolveImage = (href: string) => Uint8Array | undefined | Promise<Uint8Array | undefined>;
|
|
7
|
+
declare const DecodeSvgOptionsSchema: z.ZodObject<{
|
|
8
|
+
width: z.ZodOptional<z.ZodNumber>;
|
|
9
|
+
height: z.ZodOptional<z.ZodNumber>;
|
|
10
|
+
scale: z.ZodOptional<z.ZodNumber>;
|
|
11
|
+
background: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
12
|
+
fonts: z.ZodOptional<z.ZodArray<z.ZodInstanceOf<Uint8Array<ArrayBuffer>>>>;
|
|
13
|
+
defaultFontFamily: z.ZodOptional<z.ZodString>;
|
|
14
|
+
maxResolutionInMP: z.ZodOptional<z.ZodNumber>;
|
|
15
|
+
resolveImage: z.ZodOptional<z.ZodCustom<ResolveImage, ResolveImage>>;
|
|
16
|
+
}, z.core.$strict>;
|
|
17
|
+
export type DecodeSvgOptions = z.input<typeof DecodeSvgOptionsSchema>;
|
|
18
|
+
export interface SvgWasm {
|
|
19
|
+
/** The compiled `@resvg/resvg-wasm/index_bg.wasm` */
|
|
20
|
+
resvg?: WebAssembly.Module;
|
|
21
|
+
}
|
|
22
|
+
export interface SvgFormatOptions {
|
|
23
|
+
/**
|
|
24
|
+
* A precompiled wasm module for runtimes or bundlers where the plugin
|
|
25
|
+
* can't load resvg's wasm itself.
|
|
26
|
+
* resvg is initialized once, by the first instance that decodes, so pass
|
|
27
|
+
* the same module to every instance.
|
|
28
|
+
*/
|
|
29
|
+
wasm?: SvgWasm;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* SVG images (.svg), rendered with resvg. Only reading is supported: writing
|
|
33
|
+
* would need a raster to vector conversion.
|
|
34
|
+
*/
|
|
35
|
+
export default function svg({ wasm }?: SvgFormatOptions): {
|
|
36
|
+
mime: "image/svg+xml";
|
|
37
|
+
hasAlpha: true;
|
|
38
|
+
detect: typeof isSvg;
|
|
39
|
+
encode: () => Promise<never>;
|
|
40
|
+
decode: (data: Buffer<ArrayBufferLike>, options?: DecodeSvgOptions) => Promise<Bitmap>;
|
|
41
|
+
};
|
|
42
|
+
export {};
|
|
43
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,OAAO,EAAE,MAAM,EAAU,MAAM,aAAa,CAAC;AAE7C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAGpC,2EAA2E;AAC3E,MAAM,MAAM,YAAY,GAAG,CACzB,IAAI,EAAE,MAAM,KACT,UAAU,GAAG,SAAS,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAAC;AAE9D,QAAA,MAAM,sBAAsB;;;;;;;;;kBA4DzB,CAAC;AAEJ,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAEtE,MAAM,WAAW,OAAO;IACtB,qDAAqD;IACrD,KAAK,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,gBAAgB;IAC/B;;;;;OAKG;IACH,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAqLD;;;GAGG;AACH,MAAM,CAAC,OAAO,UAAU,GAAG,CAAC,EAAE,IAAI,EAAE,GAAE,gBAAqB;;;;;sDAU/B,gBAAgB;EAG3C"}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { Buffer } from "buffer";
|
|
2
|
+
import { initWasm, Resvg } from "@resvg/resvg-wasm";
|
|
3
|
+
import { cssColorToHex } from "@jimp/utils";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { isSvg } from "./detect.js";
|
|
6
|
+
import { loadWasm } from "./load-wasm.js";
|
|
7
|
+
const DecodeSvgOptionsSchema = z
|
|
8
|
+
.object({
|
|
9
|
+
/**
|
|
10
|
+
* Width to render at, in pixels. The height keeps the SVG's aspect ratio.
|
|
11
|
+
* With `height` too, the image fits inside both.
|
|
12
|
+
* Defaults to the SVG's own size.
|
|
13
|
+
*/
|
|
14
|
+
width: z.number().positive().optional(),
|
|
15
|
+
/**
|
|
16
|
+
* Height to render at, in pixels. The width keeps the SVG's aspect ratio.
|
|
17
|
+
* With `width` too, the image fits inside both.
|
|
18
|
+
* Defaults to the SVG's own size.
|
|
19
|
+
*/
|
|
20
|
+
height: z.number().positive().optional(),
|
|
21
|
+
/**
|
|
22
|
+
* Render at a multiple of the SVG's own size, e.g. 2 for twice the
|
|
23
|
+
* width and height. Can't be combined with `width` or `height`.
|
|
24
|
+
* @default 1
|
|
25
|
+
*/
|
|
26
|
+
scale: z.number().positive().optional(),
|
|
27
|
+
/**
|
|
28
|
+
* Fill the image with this colour behind the SVG: a CSS colour or a
|
|
29
|
+
* 0xRRGGBBAA number.
|
|
30
|
+
* @default transparent
|
|
31
|
+
*/
|
|
32
|
+
background: z.union([z.string(), z.number()]).optional(),
|
|
33
|
+
/**
|
|
34
|
+
* Fonts (TTF, OTF, TTC or WOFF2) to draw `<text>` with. Without any, text isn't
|
|
35
|
+
* drawn: the plugin has no access to system fonts.
|
|
36
|
+
*/
|
|
37
|
+
fonts: z.array(z.instanceof(Uint8Array)).optional(),
|
|
38
|
+
/**
|
|
39
|
+
* The family to use for text that doesn't set `font-family`, and for the
|
|
40
|
+
* generic `serif`, `sans-serif` and `monospace` families. Text in a family
|
|
41
|
+
* none of the `fonts` have falls back to a font that has its characters.
|
|
42
|
+
*/
|
|
43
|
+
defaultFontFamily: z.string().optional(),
|
|
44
|
+
/**
|
|
45
|
+
* Largest image, in megapixels, that will be rendered. Larger sizes are
|
|
46
|
+
* rejected before any pixel memory is allocated.
|
|
47
|
+
* @default 100
|
|
48
|
+
*/
|
|
49
|
+
maxResolutionInMP: z.number().positive().optional(),
|
|
50
|
+
/**
|
|
51
|
+
* Loads the http(s) URLs of `<image>` elements, which are otherwise
|
|
52
|
+
* skipped, by returning the PNG, JPEG or GIF's bytes. Images in `data:`
|
|
53
|
+
* URLs are always drawn.
|
|
54
|
+
*
|
|
55
|
+
* Only use this for SVGs you trust, or check the URL first: an untrusted
|
|
56
|
+
* SVG can make your server request any URL, including internal ones.
|
|
57
|
+
*/
|
|
58
|
+
resolveImage: z
|
|
59
|
+
.custom((value) => typeof value === "function")
|
|
60
|
+
.optional(),
|
|
61
|
+
})
|
|
62
|
+
.strict()
|
|
63
|
+
.refine(({ scale, width, height }) => scale === undefined || (width === undefined && height === undefined), "Pass either scale or width and height, not both");
|
|
64
|
+
let resvgReady;
|
|
65
|
+
function initResvgOnce(module) {
|
|
66
|
+
resvgReady ??= Promise.resolve(module ?? loadWasm())
|
|
67
|
+
.then((wasm) => initWasm(wasm))
|
|
68
|
+
.catch((error) => {
|
|
69
|
+
// Another copy of the plugin, or the app, has initialized it already
|
|
70
|
+
if (!(error instanceof Error && error.message.startsWith("Already"))) {
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
return resvgReady;
|
|
75
|
+
}
|
|
76
|
+
/** resvg renders premultiplied RGBA, which Jimp doesn't use */
|
|
77
|
+
function unpremultiply(pixels) {
|
|
78
|
+
// Already copied out of wasm memory, so it's converted in place
|
|
79
|
+
const data = Buffer.from(pixels.buffer, pixels.byteOffset, pixels.byteLength);
|
|
80
|
+
for (let i = 0; i < data.length; i += 4) {
|
|
81
|
+
const alpha = data[i + 3];
|
|
82
|
+
if (alpha !== 0 && alpha !== 255) {
|
|
83
|
+
for (let c = i; c < i + 3; c++) {
|
|
84
|
+
data[c] = Math.min(255, Math.round((data[c] * 255) / alpha));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return data;
|
|
89
|
+
}
|
|
90
|
+
function toHexColor(color) {
|
|
91
|
+
return `#${(cssColorToHex(color) >>> 0).toString(16).padStart(8, "0")}`;
|
|
92
|
+
}
|
|
93
|
+
/** How resvg should scale the SVG, when that doesn't depend on its size */
|
|
94
|
+
function getFit({ width, height, scale, }) {
|
|
95
|
+
if (width !== undefined && height !== undefined) {
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
if (width !== undefined) {
|
|
99
|
+
return { mode: "width", value: Math.max(1, Math.round(width)) };
|
|
100
|
+
}
|
|
101
|
+
if (height !== undefined) {
|
|
102
|
+
return { mode: "height", value: Math.max(1, Math.round(height)) };
|
|
103
|
+
}
|
|
104
|
+
return scale === undefined
|
|
105
|
+
? { mode: "original" }
|
|
106
|
+
: { mode: "zoom", value: scale };
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The size to render the SVG at, rounded like resvg does, and how resvg
|
|
110
|
+
* should scale the SVG's own size to it
|
|
111
|
+
*/
|
|
112
|
+
function getRenderSize(intrinsicWidth, intrinsicHeight, options) {
|
|
113
|
+
let { width, height } = options;
|
|
114
|
+
// Fit inside both, so whichever is smaller relative to the SVG wins
|
|
115
|
+
if (width !== undefined && height !== undefined) {
|
|
116
|
+
if (width / intrinsicWidth <= height / intrinsicHeight) {
|
|
117
|
+
height = undefined;
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
width = undefined;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const fitTo = getFit({ ...options, width, height });
|
|
124
|
+
switch (fitTo.mode) {
|
|
125
|
+
case "width":
|
|
126
|
+
return {
|
|
127
|
+
fitTo,
|
|
128
|
+
width: fitTo.value,
|
|
129
|
+
height: Math.round((fitTo.value * intrinsicHeight) / intrinsicWidth),
|
|
130
|
+
};
|
|
131
|
+
case "height":
|
|
132
|
+
return {
|
|
133
|
+
fitTo,
|
|
134
|
+
width: Math.round((fitTo.value * intrinsicWidth) / intrinsicHeight),
|
|
135
|
+
height: fitTo.value,
|
|
136
|
+
};
|
|
137
|
+
case "original":
|
|
138
|
+
return { fitTo, width: intrinsicWidth, height: intrinsicHeight };
|
|
139
|
+
case "zoom": {
|
|
140
|
+
// At least a pixel across the smaller side
|
|
141
|
+
const value = Math.max(fitTo.value, 1 / Math.min(intrinsicWidth, intrinsicHeight));
|
|
142
|
+
return {
|
|
143
|
+
fitTo: { mode: "zoom", value },
|
|
144
|
+
width: Math.round(intrinsicWidth * value),
|
|
145
|
+
height: Math.round(intrinsicHeight * value),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
async function decode(data, options, wasm) {
|
|
151
|
+
const { background, fonts = [], defaultFontFamily, maxResolutionInMP = 100, resolveImage, ...size } = DecodeSvgOptionsSchema.parse(options);
|
|
152
|
+
const renderOptions = {
|
|
153
|
+
background: background === undefined ? undefined : toHexColor(background),
|
|
154
|
+
// Only the given fonts: the wasm has no access to the system's
|
|
155
|
+
font: { fontBuffers: fonts, defaultFontFamily },
|
|
156
|
+
};
|
|
157
|
+
const fitTo = getFit(size);
|
|
158
|
+
await initResvgOnce(wasm);
|
|
159
|
+
// Parses the SVG. The pixels are only allocated by render()
|
|
160
|
+
let svg = new Resvg(data, { ...renderOptions, fitTo });
|
|
161
|
+
try {
|
|
162
|
+
const target = getRenderSize(svg.width, svg.height, size);
|
|
163
|
+
if (target.width * target.height > maxResolutionInMP * 1_000_000) {
|
|
164
|
+
throw new Error(`SVG dimensions ${target.width}x${target.height} exceed the maximum resolution of ${maxResolutionInMP} megapixels. Use the width, height or scale option to render it smaller.`);
|
|
165
|
+
}
|
|
166
|
+
// The scale depends on the SVG's size, and is a parsing option
|
|
167
|
+
if (JSON.stringify(target.fitTo) !== JSON.stringify(fitTo)) {
|
|
168
|
+
const scaled = new Resvg(data, { ...renderOptions, fitTo: target.fitTo });
|
|
169
|
+
svg.free();
|
|
170
|
+
svg = scaled;
|
|
171
|
+
}
|
|
172
|
+
if (resolveImage) {
|
|
173
|
+
for (const href of svg.imagesToResolve()) {
|
|
174
|
+
const image = await resolveImage(href);
|
|
175
|
+
if (image) {
|
|
176
|
+
svg.resolveImage(href, image);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const image = svg.render();
|
|
181
|
+
try {
|
|
182
|
+
return {
|
|
183
|
+
data: unpremultiply(image.pixels),
|
|
184
|
+
width: image.width,
|
|
185
|
+
height: image.height,
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
image.free();
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
finally {
|
|
193
|
+
svg.free();
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* SVG images (.svg), rendered with resvg. Only reading is supported: writing
|
|
198
|
+
* would need a raster to vector conversion.
|
|
199
|
+
*/
|
|
200
|
+
export default function svg({ wasm } = {}) {
|
|
201
|
+
return {
|
|
202
|
+
mime: "image/svg+xml",
|
|
203
|
+
hasAlpha: true,
|
|
204
|
+
detect: isSvg,
|
|
205
|
+
encode: async () => {
|
|
206
|
+
throw new Error("Jimp can read SVG but can't write it. Write a raster format like PNG (image/png) instead.");
|
|
207
|
+
},
|
|
208
|
+
decode: (data, options = {}) => decode(data, options, wasm?.resvg),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
//# sourceMappingURL=index.js.map
|