Convert images to Base64 data URLs for embedding.
Base64 encoding converts binary image data into a text string that can be embedded directly in HTML, CSS, or JSON. This creates a "data URL" that browsers can render as an image without making a separate HTTP request for the file.
A Base64 data URL looks like:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA...
A 10KB image becomes ~13.3KB when Base64 encoded. This overhead is offset by eliminating an HTTP request, but only for small files where the request overhead would be significant.
<!-- Direct in img tag -->
<img src="data:image/png;base64,iVBORw0KG..." alt="Icon">
<!-- In picture element for responsive -->
<picture>
<source srcset="data:image/webp;base64,..." type="image/webp">
<img src="data:image/png;base64,..." alt="Fallback">
</picture>
/* Background image */
.icon {
background-image: url("data:image/svg+xml;base64,PHN2...");
background-size: contain;
}
/* Cursor */
.custom-cursor {
cursor: url("data:image/png;base64,..."), auto;
}
/* List marker */
ul.custom-bullets li::before {
content: url("data:image/svg+xml;base64,...");
}
| Format | MIME Type | Best For |
|---|---|---|
| PNG | image/png |
Icons, graphics with transparency |
| JPEG | image/jpeg |
Photos (avoid for Base64) |
| GIF | image/gif |
Simple animations, limited colors |
| WebP | image/webp |
Modern format, good compression |
| SVG | image/svg+xml |
Icons, logos, illustrations |
# Python
import base64
with open("image.png", "rb") as f:
encoded = base64.b64encode(f.read()).decode()
data_url = f"data:image/png;base64,{encoded}"
// JavaScript (browser)
const reader = new FileReader();
reader.onload = () => console.log(reader.result);
reader.readAsDataURL(file);
// Node.js
const fs = require('fs');
const data = fs.readFileSync('image.png').toString('base64');
const dataUrl = `data:image/png;base64,${data}`;
| < 2KB | Ideal for Base64 |
| 2-10KB | Consider case-by-case |
| > 10KB | Use separate file |