Image to Base64: Embed Images in HTML and CSS — Complete Guide

Stop making separate image requests for tiny icons. Learn how Base64 encoding works, when inline images actually improve performance, and when they don't.

Development 2026-04-13 By RiseTop Team ⏱ 11 min read

What Is Base64 Encoding?

Base64 is a binary-to-text encoding scheme that represents binary data using a set of 64 printable ASCII characters: A through Z, a through z, 0 through 9, plus (+), and slash (/). The equals sign (=) is used as padding. It was originally designed for encoding binary data in email messages (MIME), but its use has expanded far beyond that original purpose.

The encoding process works by taking groups of 3 bytes (24 bits) of binary data and splitting them into 4 groups of 6 bits each. Each 6-bit value maps to one of the 64 characters. This is why Base64-encoded data is always approximately 33% larger than the original binary data — 4 characters represent 3 bytes.

For images, Base64 encoding converts the entire binary image file into a text string that can be embedded directly in HTML or CSS using a data URI scheme. This means the image data lives inside your markup or stylesheet rather than in a separate file that requires its own HTTP request.

How the Encoding Process Works — Step by Step

Let's walk through what happens when you convert an image to Base64, from a technical perspective:

Step 1: Read the binary data. The encoder reads the raw bytes of the image file. For a PNG file, this includes the PNG signature, chunk headers, compressed image data, and checksums.

Step 2: Group into 3-byte blocks. The binary data is divided into groups of 3 bytes (24 bits). If the total number of bytes isn't divisible by 3, the last group is padded with zero bytes.

Step 3: Convert to 6-bit indices. Each 24-bit group is split into four 6-bit numbers. These numbers serve as indices into the Base64 character table.

Step 4: Map to characters. Each 6-bit index is mapped to its corresponding Base64 character. Padding characters (=) are added to the output if the original data length wasn't divisible by 3.

Step 5: Create the data URI. The resulting Base64 string is prepended with a data URI scheme identifier: data:[mediatype][;base64], followed by the encoded string. For a PNG image, this looks like data:image/png;base64,iVBORw0KGgoAAAANSUhEUg...

Using Base64 Images in HTML

The most common way to use Base64 images is in the src attribute of an <img> tag:

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

The data URI replaces the URL that would normally point to an external file. The browser decodes the Base64 string back into binary image data and renders it just as it would a regular image.

You can use this technique with any image format — PNG, JPG, GIF, SVG, WebP — as long as you specify the correct MIME type in the data URI prefix:

Using Base64 Images in CSS

Base64 images work equally well in CSS, most commonly as background images:

.icon {
  background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDov...");
  background-size: contain;
  background-repeat: no-repeat;
  width: 24px;
  height: 24px;
}

This is particularly useful for small icons that are used across a site. Instead of creating separate sprite sheets or managing dozens of tiny image files, you can embed the icon data directly in your CSS.

For SVG icons specifically, there's an even more efficient approach: URL-encoding the SVG markup directly without Base64 encoding it. This avoids the 33% size increase and can produce shorter strings:

.icon {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M12 2L2 7l10 5 10-5z'/%3E%3C/svg%3E");
}

Performance Impact: The Real Story

Base64 images are often presented as a performance optimization, but the reality is more nuanced. Let's break down the actual performance characteristics:

The 33% Size Penalty

Base64 encoding always increases data size by approximately 33%. A 1 KB image becomes ~1.33 KB. A 10 KB image becomes ~13.3 KB. A 100 KB image becomes ~133 KB. This is a fixed mathematical overhead that cannot be avoided.

Request Elimination vs Size Increase

The theoretical benefit of Base64 is eliminating HTTP requests. Each HTTP request has overhead: DNS lookup, TCP handshake, TLS negotiation (for HTTPS), and request/response headers. On HTTP/1.1, browsers are limited to 6 concurrent connections per domain, so many small images can create request bottlenecks.

However, on HTTP/2 and HTTP/3, this benefit largely disappears. These modern protocols multiplex multiple requests over a single connection, eliminating the per-request overhead that made Base64 appealing. With HTTP/2, loading 20 small images is nearly as fast as loading them inline.

Decoding CPU Cost

Base64 decoding is CPU-bound. The browser must decode the Base64 string back to binary before it can parse and render the image. For small images this is negligible, but for large Base64 strings embedded in HTML, it can measurably delay page rendering. The browser can't begin rendering the image until the entire Base64 string is decoded, which blocks the main thread.

Caching Implications

⚠️ Critical caching issue: Base64 images embedded in HTML or CSS are cached as part of that HTML/CSS file. They cannot be cached independently. If your HTML file is 500 KB because it contains many Base64 images, the entire 500 KB must be re-downloaded whenever any part of the page changes. Regular image files, by contrast, benefit from independent caching with ETags, Cache-Control headers, and content delivery networks.

When Base64 Actually Helps

✅ Sweet spot: Base64 images are beneficial for files under 2-4 KB. At this size, the 33% overhead is negligible (under 1.3 KB), the request elimination matters (especially on HTTP/1.1), and the caching penalty is minimal because the image is tiny.

When to Use Base64 Images

When NOT to Use Base64 Images

Encoding Images in JavaScript

The FileReader API provides a straightforward way to encode images to Base64 in the browser:

const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.onchange = (e) => {
  const file = e.target.files[0];
  const reader = new FileReader();
  reader.onload = () => {
    const base64String = reader.result;
    // base64String = "data:image/png;base64,iVBOR..."
    console.log(base64String);
  };
  reader.readAsDataURL(file);
};

The readAsDataURL() method automatically produces a complete data URI string, including the MIME type prefix and Base64-encoded content.

Encoding Images with Command Line

For quick conversions without opening a browser, the command line is often faster:

# Using base64 (Linux/macOS)
base64 -i image.png -o image.b64

# Using OpenSSL
openssl base64 -in image.png -out image.b64

# Using Python
python3 -c "import base64; print(base64.b64encode(open('image.png','rb').read()).decode())"

Base64 vs Regular Images: Quick Comparison

AspectBase64 InlineRegular Image File
HTTP Requests0 (eliminated)1 per image
File Size+33% overheadOriginal size
Browser CachingTied to parent fileIndependent caching
CDN FriendlyNoYes
Responsive SupportNoYes (srcset, picture)
SEOPoorGood (alt, filename, sitemap)
HTTP/2 BenefitMinimalExcellent
Best Size< 2-4 KBAny size

Convert any image to Base64 instantly — paste, upload, or drag and drop.

Try Image to Base64 Converter →

Frequently Asked Questions

What is Base64 encoding and why is it used for images?

Base64 is a binary-to-text encoding scheme that converts binary data (like image files) into a string of ASCII characters. It uses a set of 64 characters (A-Z, a-z, 0-9, +, /) to represent binary data. For images, Base64 encoding allows you to embed the image data directly into HTML or CSS as a data URI, eliminating the need for separate image file requests.

Does Base64 encoding increase image file size?

Yes. Base64 encoding increases file size by approximately 33%. A 10 KB image becomes roughly 13.3 KB when Base64-encoded. This is because Base64 encodes 3 bytes of binary data as 4 characters of ASCII text. While this seems wasteful, the elimination of an HTTP request can sometimes offset this overhead for very small images.

When should I use Base64 images instead of regular image files?

Use Base64 images for very small files (under 2-4 KB) like tiny icons, 1x1 pixel tracking pixels, simple SVG patterns, or single-color placeholder images. The benefit is eliminating HTTP requests, which matters on pages with many small images. For anything larger, use regular image files — the 33% size increase of Base64 outweighs the request-saving benefit.

Can Base64 images be cached by the browser?

Base64 images embedded in HTML or CSS are cached as part of the HTML or CSS file itself. However, they cannot be cached independently — if you update a single Base64 image, the entire HTML or CSS file must be re-downloaded. Regular image files benefit from independent caching, ETags, and conditional requests, which makes them more cache-efficient for frequently updated content.

How do I convert an image to Base64 in JavaScript?

Use the FileReader API: create an input element for file selection, read the file with FileReader.readAsDataURL(), and access the result in the onload callback. The result is a complete data URI string (e.g., 'data:image/png;base64,iVBOR...') that can be used directly in src attributes or CSS background-image properties.

Related Articles