If you've ever needed to embed an image directly into HTML or CSS without a separate file, you've needed Base64 image encoding. This guide covers everything — what it is, when to use it, and how to do it in HTML, CSS, JavaScript, Python, and Node.js.
What is Base64 image encoding?
Base64 encoding converts binary data (like an image file) into a string of ASCII text characters. The result is a long string that looks like iVBORw0KGgoAAAANSUhEUgAA...
When prefixed with a MIME type, it becomes a data URI that browsers can render directly:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...
This data URI can be used anywhere a regular image URL would work — in an <img> tag, a CSS background-image, or a JSON field.
When should you use Base64 images?
Use Base64 for:
- Small icons and logos (under 5 KB) — eliminates an HTTP request
- HTML email templates — many email clients block external image URLs, so Base64 embedding guarantees images display
- Single-file offline HTML apps that can't rely on external paths
- API payloads that must carry image data as text (e.g. sending a logo in a REST API response)
Avoid Base64 for:
- Large images (over 50 KB) — the 33% size overhead adds up fast
- Images used across multiple pages — browsers can't cache Base64 inline images separately
- Images that change frequently — you'd need to redeploy code to update the image
The 33% size increase explained
Base64 encodes every 3 bytes of binary data into 4 ASCII characters. This means every image you encode becomes approximately 33% larger.
| Original | Base64 size |
|---|---|
| 5 KB icon | ~6.7 KB |
| 20 KB logo | ~26.7 KB |
| 100 KB photo | ~133 KB |
For small icons, this is acceptable. For large photos, serve them as regular files.
How to use a Base64 image in HTML
The simplest use case — an inline image:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..." alt="Logo">
The browser renders this exactly like a normal <img> tag. No network request needed.
How to use a Base64 image in CSS
Embed an image as a CSS background:
.icon {
background-image: url('data:image/png;base64,iVBORw0KGgo...');
width: 24px;
height: 24px;
background-size: contain;
}
This is a common pattern for small UI icons and spinners — keeps your CSS self-contained.
How to encode an image in JavaScript (browser)
The browser's FileReader API handles this natively:
function imageToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = e => resolve(e.target.result); // full data URI
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
// Usage with a file input:
const file = document.getElementById('fileInput').files[0];
const dataUri = await imageToBase64(file);
// Get just the raw Base64 string (strip the prefix):
const rawBase64 = dataUri.split(',')[1];
// Use in an img tag:
document.getElementById('preview').src = dataUri;
How to encode an image in Python
Python's built-in base64 module makes this straightforward:
import base64
with open('image.png', 'rb') as f:
data = base64.b64encode(f.read()).decode('utf-8')
# Raw Base64 string
print(data)
# Full data URI
uri = f"data:image/png;base64,{data}"
# Ready-to-paste HTML
html = f'<img src="{uri}" alt="image">'
# Ready-to-paste CSS
css = f"background-image: url('{uri}');"
How to encode an image in Node.js
const fs = require('fs');
const path = require('path');
function imageToBase64(filePath) {
const data = fs.readFileSync(filePath).toString('base64');
const ext = path.extname(filePath).slice(1).toLowerCase();
const mimeMap = {
png: 'image/png',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
gif: 'image/gif',
webp: 'image/webp',
svg: 'image/svg+xml',
};
const mime = mimeMap[ext] || 'image/png';
return `data:${mime};base64,${data}`;
}
const uri = imageToBase64('./logo.png');
console.log(`<img src="${uri}" alt="logo">`);
Privacy note: client-side vs server-side tools
Many online "image to Base64" converters upload your image to their server to process it. This is a privacy concern if the image contains confidential data.
This can be done entirely in the browser using the FileReader API — no upload required. The image is processed locally and never sent anywhere.
If you need a quick online tool for this, SnappyTools Image to Base64 Encoder does this 100% browser-side — drag and drop your image and get HTML, CSS, data URI, or raw Base64 output in one click.
Summary
| Format | What it looks like | When to use |
|---|---|---|
| Raw Base64 | iVBORw0KGgo... |
API payloads, further processing |
| Data URI | data:image/png;base64,... |
Direct use anywhere a URL works |
| HTML | <img src="data:..."> |
Paste into HTML files |
| CSS | background-image: url(...) |
Paste into stylesheets |
Base64 image encoding is a simple technique with clear use cases. Keep images small when embedding, and always prefer external files for larger images that need caching.
Top comments (0)