-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsvg-to-png.js
More file actions
172 lines (142 loc) · 3.82 KB
/
svg-to-png.js
File metadata and controls
172 lines (142 loc) · 3.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
/* eslint-disable max-statements */
/* eslint-disable max-lines-per-function */
/**
* @module
*
* This module provides a default exported function to convert an SVG file to a PNG file.
*/
// @ts-self-types="./types.d.ts"
import { toFileUrl } from "@std/path";
import { launch } from "@astral/astral";
const {
Command,
writeFile
} = Deno;
// TODO[2025-01-01]: Implement animated SVG
// SVGElement.pauseAnimations() to stop animation
// SVGAnimationElement.setCurrentTime() to set time
// calculate time somehow using some fps and maybe duration attributes or maybe just use 5 seconds
// export each frame to png, compare each png to correct png and take average as score
/**
* The options object for the `svgToPng` function.
*
* @typedef {object} SvgToPngOptions
* @property {number} [resizeWidth] - The width to resize the SVG to.
* @property {number} [resizeHeight] - The height to resize the SVG to.
* @property {boolean} [compress] - Whether to compress the PNG file.
*/
/**
* Converts an SVG file to a PNG file.
*
* @param {string} svgPath - The path to the SVG file.
* @param {string} pngPath - The path to the PNG file.
* @param {SvgToPngOptions} [options] - The options object.
* @returns {Promise<void>} - A promise that resolves when the PNG file has been created.
* @example
*/
const svgToPng = async (
svgPath,
pngPath,
{
compress = true,
resizeHeight,
resizeWidth
} = {}
) => {
const svgFileUrl = toFileUrl(svgPath);
const browser = await launch();
const page = await browser.newPage();
await page.goto(svgFileUrl.toString(), { waitUntil: "networkidle0" });
await page.waitForSelector("svg", { timeout: 5_000 });
const { height, width } = await page.evaluate(() => {
const svgElement = document.querySelector("svg");
if (!svgElement) {
throw new Error("SVG element not found");
}
const viewBoxString = svgElement.getAttribute("viewBox");
svgElement.removeAttribute("style");
svgElement.style.width = "revert";
svgElement.style.height = "revert";
svgElement.removeAttribute("width");
svgElement.removeAttribute("height");
const [
xString,
yString,
viewBoxWidthString,
viewBoxHeightString
] = viewBoxString?.split(" ") ?? [];
if (
viewBoxWidthString &&
viewBoxHeightString &&
document.querySelector("parsererror") === null
) {
return {
height: Number(viewBoxHeightString),
width: Number(viewBoxWidthString)
};
}
throw new Error("SVG viewBox attribute is missing or malformed or SVG code is invalid");
});
if (width !== undefined && height !== undefined) {
if (resizeWidth !== undefined && resizeHeight !== undefined) {
await page.setViewportSize({
height: resizeHeight,
width: resizeWidth
});
}
else if (resizeWidth && resizeHeight === undefined) {
await page.setViewportSize({
height: Math.round(height * (resizeWidth / width)),
width: resizeWidth
});
}
else if (resizeWidth === undefined && resizeHeight) {
await page.setViewportSize({
height: resizeHeight,
width: Math.round(width * (resizeHeight / height))
});
}
else {
await page.setViewportSize({
height,
width
});
}
const celestial = page.unsafelyGetCelestialBindings();
await celestial.Emulation.setDefaultBackgroundColorOverride({
color: {
r: 0,
a: 0,
g: 0,
b: 0
}
});
const imageContent = await page.screenshot({
captureBeyondViewport: false,
format: "png",
fromSurface: true
});
await page.close();
await writeFile(pngPath, imageContent);
if (compress) {
const compressCommand = new Command(
"oxipng",
{
args: [
"-o",
"6",
"--strip",
"safe",
pngPath
]
}
);
await compressCommand.output();
}
}
else {
throw new Error("SVG viewBox attribute is missing or malformed");
}
await browser.close();
};
export default svgToPng;