How do I encode images to Base64?
Base64 encoding images allows you to embed image data directly in HTML, CSS, or JSON.
Why Encode Images to Base64?
- Reduce HTTP requests by embedding small images inline
- Include images in JSON API responses
- Create self-contained HTML emails
- Store images in text-based databases
- Generate data URIs for CSS backgrounds
Image Data URI Format:
data:[MIME-type];base64,[BASE64-DATA]
Example:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA..." />
How to Encode Images:
- In Browser JavaScript:
// Using FileReader API
const reader = new FileReader();
reader.onload = (e) => {
const base64 = e.target.result; // Includes data URI prefix
console.log(base64);
};
reader.readAsDataURL(imageFile);
- Using Online Tools:
- Upload image to a Base64 image encoder
- Copy the resulting data URI
- Use in HTML, CSS, or JavaScript
- Command Line (Linux/Mac):
base64 image.png > image.txt
Common MIME Types:
- PNG:
image/png - JPEG:
image/jpeg - GIF:
image/gif - SVG:
image/svg+xml - WebP:
image/webp
Use Cases:
HTML:
<img src="data:image/png;base64,iVBORw..." alt="Logo" />
CSS:
.icon {
background-image: url(data:image/png;base64,iVBORw...);
}
JSON API:
{
"avatar": "data:image/jpeg;base64,/9j/4AAQSkZJRg..."
}
Best Practices:
- Only encode small images (< 10KB) - larger images should be separate files
- Use for icons, logos, and UI elements
- Consider performance impact (inline Base64 can't be cached separately)
- Compress images before encoding
- Use WebP format when possible for better compression
Drawbacks:
- 33% size increase after encoding
- Can't be cached separately from the HTML/CSS
- Harder to update images
- Makes HTML/CSS files larger
- Can impact page load performance for large images