About Base64 Image Encoding
Base64 encoding converts binary image data into a text string using 64 ASCII characters (A-Z, a-z, 0-9, +, /). This allows images to be embedded directly in HTML, CSS, or JavaScript without requiring a separate file download.
A data URI combines the Base64-encoded data with a MIME type prefix, creating a complete reference that browsers can render as an image. The format is: data:image/png;base64,iVBORw0KGgo...
When to Use Base64 Images
- Small icons and logos: For images under 2-5 KB, embedding as Base64 eliminates an HTTP request, which can be faster than loading a separate file.
- Email HTML: Many email clients block external images by default. Base64-encoded images display without the recipient needing to "load images."
- CSS backgrounds: Small decorative images or patterns can be embedded directly in CSS using
background-image: url(data:image/...). - Single-file HTML: When you need a completely self-contained HTML file with no external dependencies.
- JavaScript/JSON: When image data needs to be stored in JSON configuration files or JavaScript variables.
When NOT to Use Base64 Images
- Large images: Base64 encoding increases file size by approximately 33%. A 100 KB image becomes about 133 KB of text. For larger images, this overhead outweighs the saved HTTP request.
- Frequently changing images: Base64 images embedded in HTML or CSS cannot be cached separately. Every page load re-downloads the embedded data.
- Performance-critical pages: Large Base64 strings in HTML increase the initial document size, delaying first paint. External images can be loaded asynchronously.
The general rule: use Base64 for images smaller than 2-5 KB. For anything larger, use standard image files with proper caching headers.
Using Data URIs in Code
In HTML: <img src="data:image/png;base64,..." alt="icon" />
In CSS: background-image: url('data:image/png;base64,...');
In JavaScript: const img = new Image(); img.src = 'data:image/png;base64,...';