Converting an SVG to PNG takes one line in most tools. Getting a PNG you won't have to redo takes a few decisions first: how many pixels you need, what goes behind the icon, and how the converter treats things like currentColor or a non-square viewBox.
I start with those decisions, then go through four ways to convert, with code I ran against sharp 0.34.5 and real icon files.
In a hurry? Convert an SVG to PNG in your browserStep 1: decide the pixel size
The SVG doesn't have a resolution. The PNG will have exactly one, so choose it for the place the image is going.
The formula is display size × the highest pixel density you care about. A 24px UI icon on a 3× phone needs 72×72 pixels. Standard destinations have their own sizes:
- UI icon in a web page or email: the CSS size × 2 at minimum (48px for a 24px icon), × 3 if you target phones.
- Favicons, the Apple touch icon and web app manifest icons: each has a fixed size. The favicon guide lists them and generates all of them from one SVG.
- Social preview (
og:image): a 1200×630 canvas. Place the icon inside a larger layout rather than stretching it to fill the frame.
If you're not sure, export larger. Scaling a crisp 512px PNG down gives a clean result. Scaling a 64px PNG up never looks right.
Better still, keep the SVG and export again when a new size comes up.
Step 2: decide what is behind the icon
Most icon SVGs have no background, and PNG keeps an alpha channel, so by default you get a transparent PNG. That's usually what you want.
There are two exceptions. One is a destination that doesn't support transparency (it fills it with black or white, and a dark icon on black disappears). The other is a platform icon like the Apple touch icon, where you should supply a solid background yourself.
Either way, choose the background color yourself instead of leaving it to the tool.
Step 3: check the SVG before converting
currentColor. Icon libraries color their strokes withcurrentColorso CSS can theme them. A converter has no CSS context, socurrentColorresolves to the default color, black. I confirmed this with sharp: astroke="currentColor"line rendered as pure black (0, 0, 0). ReplacecurrentColorwith the actual hex value before converting, or set thecolorattribute on the root<svg>. Both fixes worked in sharp.viewBoxand aspect ratio. A 48×24viewBoxresized to 512×512 has to be either padded or cropped. Some tools crop by default. See the sharp section below.- External references. An SVG that uses a web font in
<text>or links an external image will render differently, or not at all, in most converters and in the browser's<img>/canvas path. Convert text to outlines in your editor first, or use the headless browser method. - Namespace. Markup copied from a page's DOM or rendered by a framework may be missing
xmlns="http://www.w3.org/2000/svg". Inline SVG doesn't need it, but a standalone file loaded as an image does.

currentColor left in, every fully opaque stroke pixel came out as 0, 0, 0. Both fixes gave 249, 250, 251 (#f9fafb).Method 1: in the browser with canvas
Every browser can already rasterize SVG, and the canvas API lets you capture the result. What matters is passing the target size to drawImage, so the browser renders the vector at that size instead of drawing it small and scaling the pixels up:
// Rasterize SVG markup to a PNG Blob in the browser.
// size: output width/height in pixels. background: e.g. '#ffffff', or null for transparent.
async function svgToPng(svgText, size, background = null) {
// An SVG loaded as an image must declare its namespace, or it fails to load.
if (!svgText.includes('xmlns=')) {
svgText = svgText.replace('<svg', '<svg xmlns="http://www.w3.org/2000/svg"');
}
const url = URL.createObjectURL(new Blob([svgText], { type: 'image/svg+xml' }));
try {
const img = new Image();
img.decoding = 'async';
img.src = url;
await img.decode(); // rejects if the SVG is invalid
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext('2d');
if (background) {
ctx.fillStyle = background;
ctx.fillRect(0, 0, size, size);
}
// Draw at the target size so the vector is rendered, not stretched.
ctx.drawImage(img, 0, 0, size, size);
return await new Promise((resolve, reject) =>
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob failed'))), 'image/png')
);
} finally {
URL.revokeObjectURL(url);
}
}
// Usage: 3x a 24px icon for high-density screens
const png = await svgToPng(document.querySelector('#logo').outerHTML, 72);Things to know about this approach:
- Tainted canvas. If you draw an image loaded from another origin without CORS headers, the canvas becomes "tainted" and
toBlob()throws aSecurityError. Building ablob:URL from markup you already have, as above, avoids that. - Sandboxed rendering. An SVG drawn through
<img>can't load external fonts, images, or stylesheets, and scripts inside it don't run. Everything the icon needs must be inside the markup. - Why not
devicePixelRatio? When you export a file, you choose the pixel count directly.devicePixelRatioonly matters when you draw a canvas that stays on screen.
Icony's PNG export works the same way. It renders the icon component to an SVG string, loads it as an image, and draws it onto a canvas that is exactly the size you picked, cleared to transparent.
If you've raised the stroke above the icon set's native width, it first widens the SVG's viewBox by half the extra width on each side, because the image is clipped to its viewBox before it ever reaches the canvas. At the native width or below, the icon fills the canvas exactly. Icony's SVG export uses the same widened viewBox, so the SVG and PNG match.
The SVG to PNG converter runs this method on your own files: it cleans the SVG, draws it at the size you pick, and keeps the viewBox proportions.
Method 2: Node.js with sharp
For build scripts and servers, sharp (which uses libvips, and librsvg for SVG) is fast and has no browser dependency. This script exports one icon at several sizes:
// npm i sharp (Node 18+; save as export-pngs.mjs)
import sharp from 'sharp';
import { mkdir } from 'node:fs/promises';
const sizes = [24, 48, 72, 512];
await mkdir('dist', { recursive: true });
for (const size of sizes) {
await sharp('icon.svg')
.resize(size, size, {
fit: 'contain', // never crop a non-square viewBox
background: { r: 0, g: 0, b: 0, alpha: 0 }, // transparent padding
})
.png()
.toFile(`dist/icon-${size}.png`);
}Two things I checked instead of taking them on faith:
densityvsresize(). Much of the advice online says to pass a highdensityor the output will be blurry. With sharp 0.34.5, resizing a 24×24 Lucide SVG to 512×512 produced byte-identical raw pixels with no density, withdensity: 300, and withdensity: 1536. sharp renders SVG input at the size you resize to.densitystill matters if you *don't* callresize(): without it, the 24×24 SVG came out as a 24×24 PNG, because the default is 72 DPI, one pixel per SVG unit.fitdefaults tocover. With a non-squareviewBox,resize(512, 512)fills the square and crops whatever overflows.fit: 'contain'with a transparent background keeps the whole icon and pads the rest. I confirmed it with a 48×24 test SVG with red caps at both ends. Withcontain, the corners were fully transparent, the center fully opaque, and all 11,360 red cap pixels were there. With the defaultcover, none were.
Here are the pixel hashes behind the first point, and the two fit results side by side:
// 24x24 Lucide house SVG -> sharp(svg, { density }).resize(512, 512).raw()
density output sha256 of the raw RGBA pixels
(none) 512x512 9242e385ffd69b130829e904efd3c3bf9c5f895944a703a038380c88e0a88188
300 512x512 9242e385ffd69b130829e904efd3c3bf9c5f895944a703a038380c88e0a88188
1536 512x512 9242e385ffd69b130829e904efd3c3bf9c5f895944a703a038380c88e0a88188
// Same file, no resize() and no density
(none) 24x24
cover, 11,360 with contain.If the destination needs a solid background, flatten the image onto a color:
// Same icon on a solid white background (e.g. for a JPEG-only uploader)
await sharp('icon.svg')
.resize(512, 512, { fit: 'contain', background: '#ffffff' })
.flatten({ background: '#ffffff' })
.png()
.toFile('icon-512-white.png');Method 3: the command line
For one-off conversions or shell pipelines, pick one of these. rsvg-convert and sharp share the same SVG renderer (librsvg), so their output should match closely.
Inkscape uses its own renderer and handles unusual SVG features well. ImageMagick hands SVG to a delegate, and the result depends on how it was built.
Always put -density before the input file, because that's when the vector is rasterized.
# librsvg (brew install librsvg / apt install librsvg2-bin)
rsvg-convert -w 512 -h 512 -o icon.png icon.svg
# Inkscape 1.x
inkscape icon.svg --export-type=png --export-width=512 --export-filename=icon.png
# ImageMagick 7: -density goes BEFORE the input file, so the vector
# is rasterized at high resolution instead of being upscaled afterwards
magick -background none -density 1536 icon.svg -resize 512x512 icon.pngTo batch a folder with rsvg-convert: for f in icons/*.svg; do rsvg-convert -w 96 -h 96 -o "png/$(basename "$f" .svg).png" "$f"; done
Method 4: a headless browser, for SVGs that depend on CSS or fonts
Some SVGs only look right inside a web page: text in a web font, styles in a <style> block that expects page CSS, or foreignObject content. Standalone renderers only approximate these.
A headless browser renders them the way users see them. Playwright can screenshot just the SVG element with a transparent background, at any device scale factor:
// npm i -D playwright && npx playwright install chromium
import { chromium } from 'playwright';
import { readFile } from 'node:fs/promises';
const svg = await readFile('badge.svg', 'utf8');
const browser = await chromium.launch();
const page = await browser.newPage({ deviceScaleFactor: 2 }); // 2x output
await page.setContent(`<body style="margin:0">${svg}</body>`);
await page.locator('svg').screenshot({ path: 'badge@2x.png', omitBackground: true });
await browser.close();It's heavier than sharp (it downloads a browser), so save it for the SVGs that need it.
Six ways a conversion goes wrong
- Upscaling a small PNG instead of re-rendering the SVG. If you have a 64px PNG and need 256px, go back to the SVG.
- A black icon where you expected a colored one. That's
currentColorresolving to black. Put a real color in the file first. - A cropped icon from a non-square viewBox. Use
fit: 'contain'(sharp) or give both width and height with a padded canvas. - Clipped strokes. Icons drawn right up to the
viewBoxedge can lose half a stroke at their extremes. Expand theviewBoxon each side by as much as the stroke reaches past it (at most half the stroke width, so a unit for a 2-unit stroke), which is what Icony's exporter does when you thicken the stroke. Drawing the image smaller on the canvas won't help, because the clipping happens inside the SVG. - Treating DPI metadata as resolution. A 512×512 PNG tagged 300 DPI and one tagged 72 DPI look identical on screen. Only the pixel count matters for the web. DPI matters only for print layout.
- Adding a white background out of habit. A white square around a logo on a dark page is the most common sign of a careless export. Keep transparency unless the destination can't handle it.
FAQ
Which method gives the "best" quality? For icon-style SVGs (paths and strokes, no text or filters), sharp, rsvg-convert, Inkscape, and browsers all produce clean anti-aliased output when you render at the target size. Quality differences mostly come from exporting at the wrong size, not from the tool. Use the headless browser when the SVG depends on CSS or fonts.
How do I make the PNG smaller? Lossless optimizers like oxipng shrink the file without changing a single pixel. For icons with few colors, pngquant's lossy palette reduction can cut the size a lot, with small changes on anti-aliased edges. Also, don't export larger than you need.
Should I convert to WebP instead? If the destination accepts WebP, lossless WebP is usually smaller than PNG. Many of the places that force you off SVG (email, older upload forms, app stores) want PNG specifically, though.
Verify the output
Before you hand the file off, confirm the pixel dimensions and that the alpha channel survived. RGBA means transparency is preserved. RGB means the background was flattened.
# Pixel size, color type, and whether there is an alpha channel
file icon-512.png
# icon-512.png: PNG image data, 512 x 512, 8-bit/color RGBA, non-interlaced
# Or, from Node
node -e "require('sharp')('icon-512.png').metadata().then(m => console.log(m.width, m.height, m.hasAlpha))"Then open the PNG on a dark background and a light one. That quickly catches a black icon on a transparent background (invisible in dark mode), halos from a background that was flattened and then removed, and strokes clipped at the edge.