Last updated
SVG to PNG Conversion
Converting SVG to PNG rasterizes the vector graphic at a specific resolution. PNG supports transparency, making it the preferred format for SVG exports when the original has transparent areas. The conversion process renders the SVG to a canvas element and exports it as a PNG blob.
High-DPI / Retina Output
async function svgToPng(svgString, outputWidth = 800) {
// Parse SVG to get viewBox dimensions
const parser = new DOMParser();
const doc = parser.parseFromString(svgString, 'image/svg+xml');
const svgEl = doc.documentElement;
const vb = svgEl.getAttribute('viewBox')?.split(/[\s,]+/).map(Number);
const srcW = vb?.[2] ?? parseFloat(svgEl.getAttribute('width') || '100');
const srcH = vb?.[3] ?? parseFloat(svgEl.getAttribute('height') || '100');
const aspect = srcH / srcW;
const canvas = document.createElement('canvas');
canvas.width = outputWidth;
canvas.height = Math.round(outputWidth * aspect);
const blob = new Blob([svgString], { type: 'image/svg+xml' });
const url = URL.createObjectURL(blob);
const img = new Image();
img.src = url;
await new Promise(r => img.onload = r);
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
URL.revokeObjectURL(url);
return new Promise(r => canvas.toBlob(r, 'image/png'));
}
// Download the PNG
async function downloadSvgAsPng(svgString, filename = 'output.png') {
const blob = await svgToPng(svgString, 1200);
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();
}
Server-Side Conversion
For server-side SVG to PNG conversion, use sharp (Node.js) or
Inkscape (command line). Sharp uses libvips and produces
high-quality output: sharp(svgBuffer).png().toFile('output.png').
For complex SVGs with web fonts or external resources, a headless browser
(Puppeteer) gives the most accurate rendering.