SVG Code to Image: Convert SVG to PNG, JPG, and WebP
SVG is the right format for resolution-independent graphics. But the moment you need to embed that icon in an email, upload it to a platform that rejects vector files, or composite it into a raster workflow, you need a conversion path from SVG code to a raster image.
This guide covers five practical methods — three CLI tools, two programming languages, and browser-based rendering — each with working code you can drop into a project. Every library version is pinned. Pick the method that fits your stack.
If you just need a quick conversion without setting up tooling, Pixotter's SVG converter handles it in your browser with no upload required.
Why Convert SVG Code to Raster Images
SVG works everywhere in theory. In practice, these situations demand raster output:
- Email clients. Outlook, Gmail, and Yahoo Mail have inconsistent SVG support. Outlook desktop renders nothing. Gmail strips inline SVG entirely. A PNG fallback is not optional — it is the only reliable path.
- Social media uploads. Twitter/X, LinkedIn, and Facebook accept PNG and JPG for image posts. None accept SVG. Open Graph and Twitter Card meta tags require raster image URLs.
- Print workflows. Prepress software handles SVG, but many print-on-demand services (Printful, Redbubble) expect PNG at specific DPI. Converting SVG to a 300 DPI PNG is standard practice.
- Legacy system integration. CMS platforms, PDF generators, and image processing pipelines often choke on SVG. A raster intermediate is the pragmatic fix.
- Canvas compositing. If you are drawing SVG content onto an HTML Canvas for screenshot generation, chart export, or WebGL textures, rasterization is a required step.
The conversion is fundamentally a rendering operation: parse the SVG DOM, lay out elements, rasterize to a pixel grid, and encode to the target format. The tools differ in how they handle fonts, CSS, external references, and edge cases like foreignObject.
Try it yourself
Convert between any image format instantly — free, instant, no signup. Your images never leave your browser.
Converting SVG to PNG and JPG with Command Line Tools
Three CLI tools handle SVG rasterization reliably. Each has different strengths.
sharp-cli (v0.33.x)
sharp wraps libvips, which uses librsvg for SVG rendering. It is fast and produces clean output for simple-to-moderate SVGs. Limited support for CSS animations and JavaScript in SVGs (which is fine — those should not be in production SVGs anyway).
License: Apache-2.0
# Install sharp-cli globally
npm install -g sharp-cli@0.33.5
# SVG to PNG at 2x density (retina)
sharp --input icon.svg --output icon.png resize 512 512
# SVG to JPG with quality control
sharp --input chart.svg --output chart.jpg --format jpeg --quality 90
# SVG to WebP
sharp --input logo.svg --output logo.webp --format webp --quality 85
For programmatic use, sharp's Node.js API is covered in the Node.js section below.
ImageMagick v7.1.1
ImageMagick delegates SVG rendering to its built-in MSVG coder or to librsvg/Inkscape if available. For complex SVGs, configuring the delegate to use Inkscape produces the most accurate results.
License: Apache-2.0 (ImageMagick License, derived from Apache-2.0)
# Verify version and SVG delegate
magick --version
# Should show: ImageMagick 7.1.1-x with SVG delegate
# Basic SVG to PNG
magick icon.svg icon.png
# Set output dimensions and density (DPI)
magick -density 300 -resize 1024x1024 diagram.svg diagram.png
# SVG to JPG with white background (SVG transparency becomes white)
magick input.svg -background white -flatten -quality 92 output.jpg
# SVG to WebP
magick input.svg -quality 85 output.webp
# Batch convert all SVGs in a directory
for f in *.svg; do
magick -density 150 "$f" "${f%.svg}.png"
done
The -density flag controls the rendering resolution before any resize. For crisp text in SVGs, use -density 150 or higher. Without it, ImageMagick defaults to 72 DPI, which produces blurry text at larger output sizes.
Inkscape v1.4
Inkscape has the most complete SVG rendering engine of any open-source tool. It handles filters, masks, clip paths, flow text, and complex CSS that trip up other renderers. If your SVG uses advanced features, Inkscape is the safe choice.
License: GPL-2.0-or-later
# SVG to PNG with specific dimensions
inkscape input.svg --export-type=png --export-filename=output.png \
--export-width=1024 --export-height=768
# SVG to PNG at 300 DPI (for print)
inkscape input.svg --export-type=png --export-filename=output.png \
--export-dpi=300
# SVG to JPG (requires export-type=jpg, available in v1.4+)
inkscape input.svg --export-type=jpg --export-filename=output.jpg \
--export-width=800
# Export specific area (crop to drawing, ignore page)
inkscape input.svg --export-type=png --export-filename=output.png \
--export-area-drawing
# Batch convert
for f in *.svg; do
inkscape "$f" --export-type=png \
--export-filename="${f%.svg}.png" --export-dpi=150
done
Inkscape launches a full application instance for each conversion, so it is slower than sharp or ImageMagick for batch operations. For bulk conversion of simple SVGs, sharp is 10-50x faster.
CLI Tool Comparison
| Feature | sharp-cli v0.33.x | ImageMagick v7.1.1 | Inkscape v1.4 |
|---|---|---|---|
| SVG rendering engine | librsvg | MSVG / librsvg delegate | Custom (most complete) |
| Output formats | PNG, JPG, WebP, AVIF, TIFF | PNG, JPG, WebP, TIFF, PDF, 200+ | PNG, JPG, PDF, EPS, EMF |
| CSS support | Basic | Basic | Full |
| Filter/mask support | Partial | Partial | Full |
| Speed (simple SVG) | Fast | Medium | Slow |
| Batch processing | Via shell loop | Built-in mogrify | Via shell loop |
| License | Apache-2.0 | Apache-2.0 | GPL-2.0 |
For most SVGs (icons, logos, simple illustrations), sharp or ImageMagick handles the job. Reserve Inkscape for SVGs that render incorrectly with the others.
For a deeper look at SVG-to-PNG specifically, see our SVG to PNG conversion guide. If JPG is your target format, the SVG to JPG guide covers quality optimization in detail.
Browser-Based SVG Rendering Methods
When you need to convert SVG to an image on the client side — for screenshot features, chart exports, or editor previews — the Canvas API is your tool.
Canvas API Approach
The Canvas API can render SVG by drawing it as an image source. The process: encode SVG as a data URI, load it into an Image element, draw it onto a canvas, then export.
/**
* Convert SVG markup to a PNG blob using Canvas API.
* Works in all modern browsers (Chrome 4+, Firefox 3.6+, Safari 3.1+).
*
* @param {string} svgString - Raw SVG markup
* @param {number} width - Output width in pixels
* @param {number} height - Output height in pixels
* @returns {Promise<Blob>} PNG image blob
*/
function svgToImage(svgString, width, height) {
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = () => {
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob((blob) => {
if (blob) resolve(blob);
else reject(new Error('Canvas toBlob returned null'));
}, 'image/png');
};
img.onerror = () => reject(new Error('Failed to load SVG as image'));
// Encode SVG as a data URI
const encoded = encodeURIComponent(svgString);
img.src = `data:image/svg+xml;charset=utf-8,${encoded}`;
});
}
// Usage
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="#3b82f6"/>
</svg>`;
const blob = await svgToImage(svg, 512, 512);
// Download or upload the blob
const url = URL.createObjectURL(blob);
Limitations of the Canvas approach:
- SVGs with external resources (linked stylesheets, images via
href) will not render. Inline everything first. foreignObjectcontent is tainted by CORS restrictions in most browsers. Chrome and Firefox blocktoBlob()on a tainted canvas.- Web fonts referenced via
@font-facewith external URLs will not load. Embed fonts as base64 data URIs within the SVG.
Handling Complex SVGs with Foreignobject
For SVGs that include HTML via foreignObject or reference external stylesheets, a headless browser approach using Puppeteer is more reliable. The Canvas API works for self-contained SVGs; Puppeteer handles everything a browser can render.
Pixotter's converter handles both simple and complex SVGs entirely in your browser — no code required, no server upload. Useful when you need a quick one-off conversion without setting up a build pipeline.
Node.js SVG to Image Conversion
sharp (v0.33.x)
sharp is the go-to image processing library for Node.js. It wraps libvips, which renders SVGs via librsvg. For server-side batch processing or build pipelines, sharp is the fastest option.
License: Apache-2.0
// npm install sharp@0.33.5
import sharp from 'sharp';
import { readFile, writeFile } from 'node:fs/promises';
// Convert SVG file to PNG
const svgBuffer = await readFile('input.svg');
await sharp(svgBuffer)
.resize(1024, 768)
.png()
.toFile('output.png');
// Convert SVG string to JPG with white background
const svgString = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<rect width="200" height="200" rx="16" fill="#6366f1"/>
<text x="100" y="110" text-anchor="middle" fill="white"
font-family="sans-serif" font-size="24">Hello</text>
</svg>`;
await sharp(Buffer.from(svgString))
.flatten({ background: { r: 255, g: 255, b: 255 } })
.jpeg({ quality: 90 })
.toFile('output.jpg');
// Convert SVG to WebP
await sharp(Buffer.from(svgString))
.webp({ quality: 85 })
.toFile('output.webp');
// Batch conversion with concurrency control
import { glob } from 'node:fs/promises';
const files = await glob('icons/*.svg');
const CONCURRENCY = 4;
for (let i = 0; i < files.length; i += CONCURRENCY) {
const batch = files.slice(i, i + CONCURRENCY);
await Promise.all(
batch.map(async (file) => {
const output = file.replace(/\.svg$/, '.png');
await sharp(file).resize(256, 256).png().toFile(output);
})
);
}
Puppeteer (v22.x)
When you need pixel-perfect rendering of complex SVGs — with CSS, animations, web fonts, or foreignObject — Puppeteer launches a headless Chrome instance and screenshots the rendered result. Slower than sharp, but handles every SVG that Chrome can render.
License: Apache-2.0
// npm install puppeteer@22.15.0
import puppeteer from 'puppeteer';
async function svgToImage(svgString, width, height, format = 'png') {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport({ width, height, deviceScaleFactor: 2 });
// Build a minimal HTML page with the SVG
const html = `<!DOCTYPE html>
<html><head><style>
* { margin: 0; padding: 0; }
body { width: ${width}px; height: ${height}px; overflow: hidden; }
svg { width: 100%; height: 100%; }
</style></head>
<body>${svgString}</body></html>`;
await page.setContent(html, { waitUntil: 'networkidle0' });
const buffer = await page.screenshot({
type: format,
omitBackground: format === 'png', // transparent background for PNG
});
await browser.close();
return buffer;
}
// Usage
import { writeFile } from 'node:fs/promises';
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 200">
<rect width="400" height="200" fill="#0f172a"/>
<text x="200" y="110" text-anchor="middle" fill="#e2e8f0"
font-family="system-ui" font-size="32">Rendered by Chrome</text>
</svg>`;
const png = await svgToImage(svg, 800, 400, 'png');
await writeFile('output.png', png);
Puppeteer is heavyweight for simple icons. Use sharp for straightforward SVGs and Puppeteer when sharp produces incorrect output (complex filters, embedded HTML, external fonts).
Python SVG to Image Conversion
CairoSVG (v2.7.x)
CairoSVG renders SVG to PNG, PDF, and PostScript using the Cairo 2D graphics library. It handles most SVG 1.1 features and produces consistent output across platforms.
License: LGPL-3.0-or-later
# pip install cairosvg==2.7.1
import cairosvg
# SVG file to PNG
cairosvg.svg2png(
url="input.svg",
write_to="output.png",
output_width=1024,
output_height=768,
)
# SVG string to PNG
svg_code = '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="45" fill="#ef4444"/>
</svg>'''
cairosvg.svg2png(
bytestring=svg_code.encode("utf-8"),
write_to="circle.png",
output_width=512,
output_height=512,
)
# SVG to PNG at 300 DPI for print
cairosvg.svg2png(url="input.svg", write_to="print.png", dpi=300)
# SVG to PDF (vector output, not rasterized)
cairosvg.svg2pdf(url="input.svg", write_to="output.pdf")
CairoSVG does not output JPG or WebP directly. Pipe through Pillow for those formats.
If you need to go beyond PNG, our SVG to PDF guide covers that workflow in depth.
CairoSVG + Pillow (v10.x) for JPG and WebP
Combine CairoSVG for rendering with Pillow for format conversion and post-processing.
Licenses: CairoSVG LGPL-3.0, Pillow HPND (permissive, similar to MIT)
# pip install cairosvg==2.7.1 Pillow==10.4.0
import io
import cairosvg
from PIL import Image
def svg_to_format(svg_path, output_path, fmt="PNG", width=1024, **kwargs):
"""Convert SVG to any Pillow-supported format."""
# Render SVG to PNG bytes via CairoSVG
png_bytes = cairosvg.svg2png(url=svg_path, output_width=width)
# Open with Pillow for format conversion
img = Image.open(io.BytesIO(png_bytes))
# JPG requires RGB mode (no alpha channel)
if fmt.upper() in ("JPEG", "JPG"):
background = Image.new("RGB", img.size, (255, 255, 255))
background.paste(img, mask=img.split()[3] if img.mode == "RGBA" else None)
img = background
img.save(output_path, format=fmt, **kwargs)
# SVG to JPG
svg_to_format("logo.svg", "logo.jpg", fmt="JPEG", width=800, quality=90)
# SVG to WebP
svg_to_format("icon.svg", "icon.webp", fmt="WEBP", width=512, quality=85)
# Batch conversion
from pathlib import Path
for svg_file in Path("icons/").glob("*.svg"):
svg_to_format(str(svg_file), str(svg_file.with_suffix(".png")), width=256)
Python Library Comparison
| Feature | CairoSVG v2.7.x | CairoSVG + Pillow | Puppeteer (via subprocess) |
|---|---|---|---|
| Direct output formats | PNG, PDF, PS | PNG, JPG, WebP, TIFF, BMP | PNG, JPG, WebP |
| SVG feature support | SVG 1.1, partial SVG 2 | Same as CairoSVG | Full (Chrome engine) |
| External font support | System fonts only | Same | Web fonts via CSS |
| Speed | Fast | Fast | Slow (browser startup) |
| Dependencies | Cairo C library | Cairo + Pillow | Chrome/Chromium binary |
| License | LGPL-3.0 | LGPL-3.0 + HPND | Apache-2.0 |
For most Python projects, CairoSVG with Pillow covers the common cases. Use Puppeteer via subprocess only when CairoSVG fails to render complex SVG features correctly.
Online SVG to Image Converter Tools
When you need a quick conversion without writing code or installing dependencies, browser-based tools are the fastest path. Here is how the major options compare:
| Tool | Formats | Batch | API | Cost | Processing |
|---|---|---|---|---|---|
| Pixotter | PNG, JPG, WebP, AVIF | Yes | Planned | Free | Client-side (WASM) |
| CloudConvert | PNG, JPG, WebP, TIFF, PDF | Yes | Yes | 25 free/day, then $0.02/file | Server-side |
| Convertio | PNG, JPG, WebP, BMP | Yes | Yes | 10 free/day, paid from $9.99/mo | Server-side |
| SVG2PNG.com | PNG only | No | No | Free | Server-side |
| SVGOMG | SVG optimization only | No | No | Free | Client-side |
Why client-side processing matters: Server-based converters upload your SVG to a third-party server. If your SVGs contain proprietary designs, internal diagrams, or pre-release branding, that is a data exposure risk. Client-side tools like Pixotter process everything in your browser — nothing leaves your machine.
Not sure whether SVG or PNG is the right starting format for your project? Our SVG vs PNG comparison breaks down when each format is the better choice. And if you need to go the other direction — raster to vector — check out how to vectorize an image.
FAQ
What is the best format to convert SVG code to?
PNG for graphics with transparency (icons, logos, UI elements). JPG for photographs or complex gradients where file size matters more than transparency. WebP for web delivery where browser support is acceptable — it produces smaller files than both PNG and JPG at equivalent quality. For print, use PNG at 300 DPI.
Can I convert SVG to image without losing quality?
SVG is vector, so it has no inherent pixel resolution. The "quality" of the raster output depends entirely on the dimensions and DPI you choose. Render at 2x your display size for retina-sharp results. There is no quality loss in the conversion itself — only in choosing too small an output size.
Why does my converted SVG look different from the browser?
Different rendering engines interpret SVG differently. librsvg (used by sharp and ImageMagick) handles 90% of SVGs correctly but struggles with advanced CSS, foreignObject, and some SVG 2.0 features. If the output looks wrong, try Inkscape or Puppeteer — both use more complete rendering engines. Also check for external resource references (fonts, images) that may not resolve outside the browser.
How do I handle SVGs with transparent backgrounds?
PNG and WebP support transparency natively. Export to either format and the transparent areas carry through. For JPG (which has no alpha channel), you need to flatten the image onto a solid background. In sharp: .flatten({ background: '#ffffff' }). In ImageMagick: -background white -flatten. In Python: composit the RGBA image onto an RGB canvas.
What is the maximum SVG size I can convert?
This depends on the tool. sharp handles SVGs up to several thousand pixels wide without issues. ImageMagick has configurable resource limits in policy.xml — the default allows images up to 16384x16384 pixels (adjustable). Puppeteer is limited by Chrome's maximum texture size, typically 16384x16384 on most GPUs. For very large SVGs (architectural diagrams, detailed maps), render in tiles and stitch.
How do I preserve fonts when converting SVG code to an image?
Three approaches: (1) Convert text to paths in the SVG before conversion — this guarantees exact rendering but makes text non-searchable. In Inkscape: select text, Path > Object to Path. (2) Embed fonts as base64 @font-face declarations inside the SVG's <style> block. (3) Ensure the fonts are installed on the system running the conversion. Options 1 and 2 are portable; option 3 depends on the environment.
Can I batch convert hundreds of SVG files efficiently?
Yes. sharp with Node.js is the fastest option for batch conversion — it processes hundreds of simple SVGs per second with controlled concurrency. Use the batch example in the Node.js section. For Python, CairoSVG with multiprocessing handles batch work well. Avoid Inkscape and Puppeteer for large batches — the per-file startup overhead makes them 10-50x slower than library-based approaches.
Is there a way to convert SVG to image entirely in the browser?
Yes. The Canvas API approach described in the browser methods section works in all modern browsers. For a zero-code option, Pixotter's converter runs entirely client-side using WebAssembly — drop your SVG, pick your output format, and download the result. No server upload, no installation.
Try it yourself
Ready to convert formats? Drop your image and get results in seconds — free, instant, no signup. Your images never leave your browser.