How to Encode Images as Base64 Data URIs in HTML and CSS
A data URI is a URL scheme that lets you embed file contents directly in HTML or CSS instead of referencing an external file. For images, the content is Base64-encoded and prefixed with the MIME type. This eliminates an HTTP request for that asset — useful for small icons, loading spinners, and email templates where external URLs may be blocked.
Data URI format
data:[<mediatype>][;base64],<data> # PNG example data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA... # SVG example (can be URL-encoded instead of Base64) data:image/svg+xml;base64,PHN2ZyB4bWxucz0i...
Using a data URI in HTML
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" alt="1x1 red pixel" width="1" height="1" />
Using a data URI in CSS
.loading-spinner {
background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL...");
background-repeat: no-repeat;
width: 24px;
height: 24px;
}
/* Inline favicon in HTML head */
<link rel="icon" href="data:image/png;base64,iVBORw0KGgo..." />Encoding an image in JavaScript (browser)
// From a file input
const fileInput = document.getElementById('file-input');
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = () => {
// reader.result is the full data URI string
document.getElementById('preview').src = reader.result;
console.log(reader.result); // data:image/png;base64,...
};
reader.readAsDataURL(file);
});Encoding an image in Node.js
import fs from 'fs';
import path from 'path';
function imageToDataUri(filePath) {
const ext = path.extname(filePath).slice(1).toLowerCase();
const mimeMap = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', svg: 'image/svg+xml', webp: 'image/webp' };
const mime = mimeMap[ext] || 'application/octet-stream';
const base64 = fs.readFileSync(filePath).toString('base64');
return `data:${mime};base64,${base64}`;
}
const dataUri = imageToDataUri('./logo.png');
// Embed in an HTML template
const html = `<img src="${dataUri}" alt="Logo" />`;When to use data URIs — and when not to
- ✅ Good for: small icons (under 5 KB), email templates, single-file HTML deliverables, favicons, inline SVG icons.
- ✅ Good for: eliminating HTTP requests for critical above-the-fold images.
- ❌ Avoid for: large images — Base64 increases size by ~33% and inflates your HTML/CSS file, hurting parse time.
- ❌ Avoid for: images shared across many pages — they can't be cached independently when inlined.
- ❌ Avoid for: SVGs that change at runtime — use an external
<img>or inline<svg>tag instead.
Encode and decode Base64 instantly
Use our free Base64 Encoder / Decoder to quickly encode text strings for use in data URIs or test decoding. For full image-to-data-URI conversion, use the JavaScript FileReader snippet above in your browser console.