Base64 Images: How Data URIs Work and When to Use Them
A Base64 image is a picture written as plain text. Wrapped in a data URI, it can be placed directly in HTML, CSS, JSON or an email without a separate file. That convenience has trade-offs in size and caching, so it pays to know when inlining helps and when it hurts.
Anatomy of a data URI
A data URI has a media type, the word base64 and the encoded data:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...Using it in HTML and CSS
Use it anywhere a URL is accepted. Keep inlined images tiny, because they cannot be cached separately and they make your HTML or CSS heavier.
<img src="data:image/png;base64,..." alt="Logo" width="32" height="32">
.icon { background-image: url("data:image/svg+xml;base64,..."); }Recognising the format
The first characters reveal the file type: iVBOR is PNG, /9j/ is JPEG, R0lGOD is GIF, UklGR is WebP and PHN2Zy is SVG. If an image fails to display, the string may be truncated or contain extra characters such as quotes from JSON.
Decoding in code
To save a Base64 image to disk from the command line:
echo 'iVBORw0KGgo...' | base64 --decode > image.png