Embedding images with Base64
Encoding an image as Base64 converts binary bytes into ASCII so the asset can live inside CSS, HTML, or JSON without separate network requests.
What the encoding does
Every three bytes become four Base64 characters, which explains the ~33% size overhead compared to the original file.
Browsers decode the string back into bytes on demand, so the rendered pixels look identical to the original asset.
When inlining helps
Inlining icons or logos can reduce HTTP requests on simple landing pages or emails where each request hurts latency.
Larger images, however, should remain separate files so CDNs can cache them and browsers can stream them progressively.
Handling different formats
PNG and JPEG encode straightforwardly, while SVG benefits from minification before conversion to avoid unnecessary characters.
For animated assets, consider WebP or AVIF before encoding so the Base64 string starts from the smallest possible binary.
Use cases that benefit
- Inlining small UI icons or favicons inside CSS
- Embedding placeholder illustrations inside component libraries
- Running automated tests that compare Base64 fixtures instead of binary files
- Bundling sprites with browser extensions where file I/O is restricted
Best practices
- Compress and strip metadata before encoding to offset the Base64 overhead
- Break extremely long strings into chunks if storing them in configuration files
- Validate MIME types and sanitize SVGs when processing user-generated files
- Prefer data URIs (data:image/png;base64,...) only for assets below a few kilobytes