How to Base64 Encode Images (Data URIs Explained)

Published: 2023-11-20 | Category: Web & API

In traditional web development, images are loaded by providing a URL path (<img src="/images/logo.png">), prompting the browser to make a separate HTTP request to fetch the file.

However, you can completely bypass the HTTP request by embedding the image directly into your HTML or CSS using a Base64 Data URI.

What is a Data URI?

A Data URI is a scheme that allows you to include data in-line in web pages as if they were external resources. It relies heavily on Base64 encoding to represent the binary image data safely as text.

The syntax of a Data URI looks like this:

Data URI Syntax
data:[][;base64],

HTML and CSS Examples

Embedding an Image in HTML

HTML
<!-- A tiny 1x1 transparent pixel encoded in Base64 -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=" alt="Pixel" />

Embedding an Image in CSS

This technique is frequently used for small UI icons or background patterns to prevent render-blocking HTTP requests.

CSS
.icon-check {
    background-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCI+PHBhdGggZD0iTTIwIDZMNCAxOEw0IDZ6Ii8+PC9zdmc+');
    width: 24px;
    height: 24px;
}

The Pros and Cons of Base64 Images

The Advantages

The Disadvantages (The 33% Penalty)

When Should You Use Base64 Images?

Do use Base64 for:

Do NOT use Base64 for:

Conclusion

Base64 Data URIs are a powerful tool for frontend optimization and single-file distributions, provided you respect their limitations. Overusing them will destroy your page load performance due to the 33% encoding overhead and synchronous parsing blocks.