Skip to content

Guide

Base64 images and data URIs: when inlining helps or hurts

By Vishnu KumarPublished 5 min read

Turning an image into a Base64 data URI lets you paste it straight into CSS, HTML or JSON with no separate file. It is also one of the most over-applied front-end tricks. This guide shows the exact cost, what compression and caching change, and a clear rule for when to inline.

What a data URI is

A data URI carries a file's bytes inside the URL itself. Its shape is data:[media type][;base64],<data>:

<img alt="dot" width="1" height="1"
     src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=">

The browser decodes the text back into bytes and treats them exactly as if it had downloaded pixel.png. The same URL works anywhere a URL is accepted: src attributes, CSS url(), fetch(), and canvas images.

Base64 is needed because URLs and most text formats cannot carry raw binary safely. It maps every 3 bytes to 4 characters from a 64-character alphabet (A–Z, a–z, 0–9, + and /), padding the end with =.

Exactly how much bigger

Base64 output is 4 × ⌈n ÷ 3⌉ characters for n input bytes, so it is a third larger, plus a few bytes of padding and the data:image/png;base64, prefix.

Original size against Base64 length
OriginalBase64 charactersIncrease
100 bytes13636%
1 KB (1,024 bytes)1,36833.6%
4 KB5,46433.4%
10 KB13,65633.4%
100 KB136,53633.3%
1 MB1,398,10433.3%

What compression gives back, and what it does not

If the page or stylesheet is served with gzip or Brotli, most of that third comes back over the wire, because Base64 uses only 6 bits of every 8-bit character and compressors notice. In a measurement on 30,000 bytes of incompressible data (which behaves like an already-compressed PNG or JPEG), the Base64 text was 40,000 characters and compressed back to 30,311 bytes with gzip, only about 1% above the original.

So the transfer cost is smaller than the table suggests. The other costs remain:

  • No separate caching. An inlined image is re-downloaded every time the document containing it changes. A 20 KB logo inlined into a stylesheet is downloaded again with every CSS deploy, instead of staying cached for a year as a file would.
  • Render blocking. Images inside CSS are part of a render-blocking resource; the page cannot paint until the whole stylesheet, images included, has arrived and been parsed.
  • No lazy loading or priority hints. The browser cannot defer an inlined image below the fold or fetch it at low priority.
  • Decoding work and memory. The text has to be decoded before the image can be decoded, and the string itself stays in memory as part of the document or stylesheet.
  • Duplication. The same icon used in three places is three copies, unless you reference it once from a class.

HTTP/2 and HTTP/3 made the original argument for inlining (saving a request) much weaker: many small requests share one connection cheaply. Inlining now saves a round trip only when the resource is discovered late, such as an image referenced from CSS.

When inlining is worth it

  • Tiny, critical images: a small icon or background under about 1–2 KB that must appear with the first paint.
  • Single-file deliverables: an HTML report, an offline page or an embeddable widget that must work as one file.
  • Test fixtures and API payloads: an image inside a JSON request body, a snapshot test or a seed file.
  • Generated images: canvas.toDataURL() output you are about to upload or store anyway.

And when it is not: photographs, anything above a few kilobytes, images shared across pages (logos, avatars), and images below the fold. Serve those as files with long cache lifetimes.

Many email clients, including Gmail, do not display data-URI images. For email, attach the image with a Content-ID or link to a hosted file.

SVG: skip Base64 entirely

SVG is text, so it can be inlined without Base64 at all, which is smaller and stays readable. URL-encode the characters that matter and use single quotes inside:

/* Base64: opaque and about a third larger */
.check { background: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0i..."); }

/* URL-encoded: smaller, readable, editable */
.check {
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M2 8l4 4 8-8' fill='none' stroke='%23000' stroke-width='2'/%3E%3C/svg%3E");
}

At minimum, encode <, >, # and %. Even better, put the SVG directly in the HTML, where it can also inherit currentColor from the text around it. See SVG by hand for writing small icons like this one.

Converting, in code

In the browser, FileReader produces a data URI from a file the user picked, without uploading it:

function toDataUri(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result); // "data:image/png;base64,..."
    reader.onerror = () => reject(reader.error);
    reader.readAsDataURL(file);
  });
}

Avoid btoa() on arbitrary text: it accepts only characters in the Latin-1 range and throws on anything else. For bytes, Node.js has it built in:

import { readFile } from "node:fs/promises";
const bytes = await readFile("logo.png");
const uri = `data:image/png;base64,${bytes.toString("base64")}`;
# GNU coreutils (Linux): -w0 disables line wrapping
base64 -w0 logo.png
# macOS
base64 -i logo.png
import base64, pathlib
data = pathlib.Path("logo.png").read_bytes()
uri = "data:image/png;base64," + base64.b64encode(data).decode("ascii")

For a folder of icons, Img2Base64 converts many images at once in the browser and shows each result's length, so the ones too large to inline are obvious before you paste them anywhere.

The rule of thumb

Inline an image only if it is small (a couple of kilobytes at most), needed for the first paint, and used in one place, or if the deliverable must be a single file. Everything else should be a file, compressed, cached and loaded at the right priority.