Back to Blog
Developer Tools

Base64 Encode Images for Data URIs โ€” Embed Images in HTML and CSS

2026-06-03 5 min read

Data URIs embed images directly in HTML or CSS as Base64 strings, eliminating HTTP requests. Here is when this is useful and how to encode them.

Data URIs let you embed images directly into HTML or CSS without a separate file request. The image is Base64-encoded and placed inline in the src attribute or as a CSS background-image value. There are real use cases for this, and also situations where it hurts more than it helps.

What a data URI looks like

The format is: data:[mediatype];base64,[encoded data]

In practice, for a small PNG icon in HTML:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..." alt="icon" />

And the same in CSS:

.icon {
  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUh...");
}

How to create one

In the browser, you can use the Canvas API or FileReader:

// From a File object (e.g., from input[type=file])
const reader = new FileReader();
reader.onload = (e) => {
  const dataUri = e.target.result;
  // "data:image/png;base64,iVBORw0KGgoAAAA..."
};
reader.readAsDataURL(file);

In Node.js:

import fs from "fs";
const imageBuffer = fs.readFileSync("./icon.png");
const base64 = imageBuffer.toString("base64");
const dataUri = `data:image/png;base64,${base64}`;

When data URIs make sense

Small icons and SVGs are the best candidates. An icon that's 200 bytes as a PNG becomes roughly 267 bytes as Base64 (Base64 adds about 33% overhead). That's still small, and embedding it saves an HTTP request.

Critical above-the-fold images are another good case. If a small logo is needed for the first paint of your page, embedding it removes one render-blocking request.

When data URIs are a bad idea

Large images are the problem case. A 100 KB image becomes 133 KB as Base64, and that data gets embedded in your HTML or CSS file. This means the browser can't cache the image separately. Each page load re-downloads the Base64 string along with the markup. For anything over about 5 KB, serving the image as a separate file with proper caching headers is almost always better.

Base64-encode your images quickly with our Base64 Encoder.

base64 data-uri image html css embed

More Articles