How to Embed Images Using Base64 Data URIs
Embedding Images with Base64 Data URIs
Data URIs allow you to embed images directly in your HTML or CSS, eliminating the need for separate HTTP requests.
What is a Data URI?
A Data URI is a way to include data inline in web pages. The format is:
`` data:[
`
For images:
` data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA...
`
Benefits of Base64 Images
Advantages:
- Fewer HTTP requests - Image loads with the HTML
- No external dependencies - Self-contained pages
- Works offline - No need to fetch from server
- Avoids CORS issues - Data is inline
Disadvantages:
- 33% larger file size - Base64 overhead
- No caching - Can't cache separately from HTML
- Harder to maintain - Can't edit image easily
- Slower initial load - Larger HTML file
When to Use Base64 Images
Good for:
- Small icons and logos (< 10KB)
- Images that appear on every page
- Email templates
- Single-page applications
- Embedded widgets
Avoid for:
- Large images (> 10KB)
- Images that change frequently
- Multiple unique images
- Performance-critical pages
HTML Implementation
In an img tag:
`html
`
In CSS background:
`css
.icon {
background-image: url('data:image/svg+xml;base64,PHN2Zy...');
}
`
Converting Images to Base64
Using JavaScript (Browser):
`javascript
function imageToBase64(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.readAsDataURL(file);
});
}
`
Using Command Line:
`bash
base64 image.png | tr -d '\n'
`
Using Online Tools:
Use Base64Spark to quickly convert any image to Base64!
SVG vs Raster Images
SVG images are especially well-suited for Base64 embedding:
- Already text-based
- Smaller file sizes
- Scale perfectly
- Can be further optimized
`html
``
Best Practices
Performance Comparison
| Method | First Load | Cached Load | Total Requests |
|--------|------------|-------------|----------------|
| External | 100ms | 10ms | 2 |
| Base64 | 80ms | 80ms | 1 |
Base64 is faster for first load but doesn't benefit from caching.