## What Is Base64 for Images?
**Base64** converts binary data (like images) into ASCII text. By encoding an image as Base64, you can include it directly in HTML, CSS, or JSON without needing an external file. Size increases by ~33%.
## Syntax: Data URI
```html
.logo {
background-image: url('data:image/png;base64,iVBORw0KGgo...');
}
```
**Format:** `data:[MIME type];base64,[encoded data]`
## Convert Image to Base64
### With Python
```python
import base64, mimetypes
def image_to_base64(path, mime=None):
if mime is None:
mime, _ = mimetypes.guess_type(path)
with open(path, "rb") as f:
data = base64.b64encode(f.read()).decode("utf-8")
return f"data:{mime};base64,{data}"
uri = image_to_base64("logo.png")
```
### With JavaScript (Browser)
```javascript
function imageToBase64(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(file);
});
}
// Using Canvas (for loaded img elements)
function imgToBase64(img, format = 'image/png') {
const canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
canvas.getContext('2d').drawImage(img, 0, 0);
return canvas.toDataURL(format);
}
```
### With Node.js
```javascript
const fs = require('fs'), path = require('path');
function imageToBase64(imagePath) {
const ext = path.extname(imagePath).slice(1).toLowerCase();
const mimes = { png:'image/png', jpg:'image/jpeg', webp:'image/webp' };
const mime = mimes[ext] || 'application/octet-stream';
const data = fs.readFileSync(imagePath).toString('base64');
return 'data:' + mime + ';base64,' + data;
}
```
### Command Line
```bash
# Linux/macOS
base64 -w 0 image.png
echo "data:image/png;base64,$(base64 -w 0 image.png)"
```
## When to Use (and When Not To)
### β
Use Base64 for:
- **Small icons** (<5 KB) β HTTP overhead exceeds savings.
- **HTML emails** β avoids blocked external images.
- **Offline apps** β no external server dependency.
- **JSON APIs** β when images are part of a payload.
### β Avoid for:
- **Large images** β increases size ~33% and breaks browser cache.
- **Reused images** β browser cache doesn't work with Data URIs.
- **Image SEO** β search engines index Base64 images poorly.
## Size Limits by Context
| Context | Recommended limit |
|---------|-----------------|
| HTML/CSS | < 5 KB |
| HTML email | < 50 KB |
| JSON API | < 100 KB |
## Conclusion
**Base64 image encoding** is valid for small icons, HTML emails, and JSON APIs. For general web content images, use conventional external URLs with caching and lazy loading.
Guide