Blog · How-To

SVG to Base64: Embed Vector Graphics in HTML

Convert SVG files to Base64 for inline embedding in HTML, CSS backgrounds, and data URIs. Smaller than PNG, scales infinitely, and renders at any resolution.

SVGs are already text. Why encode them? Because embedding an SVG as Base64 in a data URI avoids certain escaping issues and lets you use the same image in CSS background-image properties cleanly. It also protects against SVG injection in user-generated content.

JavaScript: SVG Element to Base64

const svg = document.querySelector("svg");
const xml = new XMLSerializer().serializeToString(svg);
const b64 = btoa(unescape(encodeURIComponent(xml)));
const dataUri = `data:image/svg+xml;base64,${b64}`;

Python: SVG File to Base64

import base64

with open("icon.svg", "rb") as f:
    b64 = base64.b64encode(f.read()).decode()

# CSS background-image usage
css = f"background-image: url(data:image/svg+xml;base64,{b64});"

Inline SVG vs Base64 SVG

FeatureInline SVGBase64 SVG
CSS customisationYes (fill, stroke via CSS)No (static image)
Security (UGC)Risky (script injection)Safe (no script execution)
CacheableOnly as part of HTMLCan be cached in CSS
SizeRaw SVG size~33% larger than raw

For quick conversion of any image or SVG to Base64, use our free online tool. Drag, drop, and get the encoded string instantly.

Convert SVG to Base64 now

Drop any SVG or image file. Get Base64 output instantly.

Open Base64 Tool