Base64 image encoding converts binary image files (PNG, JPG, SVG, WebP) into plain-text data URLs. This allows you to embed images directly inside HTML, CSS, or JSON without requiring an external HTTP request.
Code Examples: How to use Base64 images
1. In HTML <img> tags
<img src="data:image/png;base64,iVBORw0KGgoAAAANS..." alt="Embedded icon" width="32" height="32" />
2. In CSS stylesheets (Background images)
.badge {
background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0...");
background-repeat: no-repeat;
}3. In JavaScript with FileReader API
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
reader.readAsDataURL(file);
});
}When should you use Base64 images?
- Small UI icons and favicons (under 10KB) to reduce round-trip HTTP requests.
- HTML email templates where external images are frequently blocked by email clients.
- Offline web applications and single-file HTML distributions.
The performance trade-off, honestly
Base64 inflates binary by about 33 percent, keeps the browser from caching the image separately, and forces the whole blob through the HTML document. Inline Base64 is a reasonable choice for tiny, never-changing assets (a logo or a 1×1 spacer below a few KB) and for images delivered straight from a database. It is the wrong tool for a 2 MB photo: the page HTML alone becomes large enough to slow first render.
- Use inline Base64 under ~10 KB and where the asset never varies.
- Keep real files as <img src> URLs so browsers can cache them.
- If a base64 image must be large, lazy-load it like any other resource.
For images the page needs immediately but cannot cache — embeds, attachments, and email signatures — this approach is not lazy: it trades bytes for guaranteed availability. The bigger the embed, the larger the tax: 750 KB in, roughly 1 MB out. Applying it to a 30 KB logo costs nothing; to a 3 MB photo, everything.
Frequently asked questions
Place the data URL directly in the src attribute of an <img> tag: <img src="data:image/png;base64,iVBORw..." alt="Icon" />
Use it in the url() property: .icon { background-image: url("data:image/png;base64,iVBORw..."); }
Use the FileReader API: const reader = new FileReader(); reader.onload = () => console.log(reader.result); reader.readAsDataURL(file);
Yes. Base64 encoding increases file size by approximately 33%. It is best used for small icons and thumbnails under 10KB.