← All Posts

How to Convert Images to Base64 (Data URIs Explained)

Published on February 10, 2026

If you have ever inspected a webpage's source code and seen a long string of seemingly random characters inside an img tag's src attribute, you were looking at a base64-encoded image embedded as a data URI. This technique allows you to include image data directly within HTML, CSS, or JavaScript without making a separate HTTP request to fetch the file. In this guide, we will break down how base64 encoding works, what data URIs are, and when this approach is beneficial versus when it hurts performance.

What Is Base64 Encoding?

Base64 is a binary-to-text encoding scheme that represents binary data using a set of 64 printable ASCII characters. The character set consists of the uppercase letters A through Z (26 characters), lowercase letters a through z (26 characters), digits 0 through 9 (10 characters), and the symbols + and / (2 characters), for a total of 64. The = character is used as padding when the input length is not a multiple of three bytes.

The encoding process works by taking three bytes (24 bits) of binary input at a time and splitting them into four groups of 6 bits each. Each 6-bit group maps to one of the 64 characters. Because 3 bytes of input become 4 characters of output, base64-encoded data is approximately 33% larger than the original binary data. This size increase is an important factor when deciding whether to use base64 for images.

What Are Data URIs?

A data URI (often called a data URL) is a URI scheme defined in RFC 2397 that allows you to embed small files inline within HTML or CSS. The syntax follows this pattern:

data:[mediatype][;base64],data

For an image, a data URI looks like this:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...

The mediatype portion specifies the MIME type of the embedded content, such as image/png, image/jpeg, image/svg+xml, or image/webp. The ;base64 flag tells the browser that the data portion is base64-encoded rather than percent-encoded text.

When to Use Base64-Encoded Images

Base64 embedding is not a universal solution. It shines in specific situations and causes problems in others. Here are the scenarios where it makes sense.

Small Icons and UI Elements

For tiny images under 2-4 KB, the overhead of a separate HTTP request (DNS lookup, TCP handshake, TLS negotiation, request and response headers) often exceeds the cost of embedding the data inline. Small icons, loading spinners, single-color decorative elements, and UI indicators are excellent candidates. The 33% size increase from base64 encoding is negligible at these file sizes.

CSS Background Images

Embedding small images directly in CSS eliminates render-blocking requests that can delay the first paint. This is particularly useful for critical above-the-fold decorative elements. The syntax in CSS looks like this:

.icon-search {
  background-image: url(data:image/svg+xml;base64,PHN2ZyB4...);
  background-size: contain;
}

This technique is especially powerful when combined with CSS sprites for very small icons that would otherwise each require their own network request.

HTML Email Templates

Email clients have notoriously inconsistent support for external images. Many block external images by default and display a "click to load images" prompt. Embedding small images as data URIs ensures they display immediately without user interaction. Note that some email clients have size limits for data URIs (Outlook, for instance, has historically had issues), so test thoroughly.

Single-File HTML Documents

When you need to distribute a completely self-contained HTML file, such as a report, invoice, or documentation page, data URIs let you embed all images within the single file. The recipient does not need a web server or an internet connection to view the images.

Reducing HTTP/1.1 Request Overhead

Under HTTP/1.1, browsers open a limited number of parallel connections per domain (typically 6). Each small image consumes one of these connection slots. Embedding reduces the total request count. However, with HTTP/2 and HTTP/3 multiplexing many requests over a single connection, this advantage has diminished significantly.

When NOT to Use Base64-Encoded Images

Understanding when to avoid base64 is just as important as knowing when to use it.

Large Images

A 100 KB JPEG becomes approximately 133 KB when base64-encoded. More critically, the encoded string is embedded in the HTML or CSS document, which means the browser cannot cache the image independently. Every page load re-downloads the image data as part of the HTML payload. For images above 5-10 KB, a separate file with proper cache headers is almost always more efficient.

Frequently Changing Pages with Static Images

If your page content changes often but the images remain the same, embedding images in the HTML means the browser must re-download the image data every time the HTML changes. Separate image files with long cache durations would be served from the browser cache on repeat visits.

Content Security Policy Restrictions

Some Content Security Policy (CSP) configurations restrict data URIs. If your site's CSP does not include data: in the img-src or style-src directives, base64 images will be blocked by the browser.

Server-Side Rendering Performance

When using server-side rendering, embedding large base64 strings inflates the HTML payload significantly. This increases Time to First Byte (TTFB) and delays parsing. The browser must download the entire HTML document before it can begin rendering, and large inline data slows this process.

Performance Trade-Offs in Detail

Let us examine the specific performance implications of base64 encoding.

File Size Increase

Base64 encoding increases the data size by approximately 33%. A 3 KB icon becomes about 4 KB. While gzip or brotli compression on the HTML document recovers some of this overhead (base64 text compresses reasonably well), the compressed base64 data is still larger than the compressed original binary.

Caching Behavior

This is the most significant trade-off. A separate image file can be cached independently with its own cache headers and expiration time. When embedded in HTML or CSS, the image data is cached only as part of that document. If the document changes, the image data must be re-downloaded even if the image itself has not changed.

Parse and Decode Time

The browser must parse the base64 string and decode it back to binary before rendering. For small images, this is negligible. For many large embedded images, the cumulative decode time can delay rendering. Modern browsers handle this efficiently, but it is still an additional step compared to loading a binary image file directly.

Memory Usage

During parsing, the browser holds both the base64 string and the decoded binary in memory simultaneously. For a page with many embedded images, this can meaningfully increase memory consumption, particularly on memory-constrained mobile devices.

How to Use Base64 Images in HTML

The simplest usage is directly in an img tag:

<img src="data:image/png;base64,iVBORw0KGgoAAAA..." alt="icon" width="24" height="24" />

You can also use data URIs in the srcset attribute for responsive images, though this is uncommon since responsive images are typically larger files that benefit from separate caching.

How to Use Base64 Images in CSS

In CSS, data URIs work anywhere you would use a url() function:

.logo {
  background-image: url(data:image/svg+xml;base64,PHN2ZyB...);
}

.divider {
  border-image: url(data:image/png;base64,iVBORw0...) 1;
}

.cursor-custom {
  cursor: url(data:image/png;base64,iVBORw0...), auto;
}

When embedded in CSS files, the images benefit from the CSS file's cache headers. If your CSS changes infrequently, this is a good middle ground between separate image files and HTML embedding.

Converting Images Programmatically

In JavaScript (browser environment), you can use the FileReader API to convert a file to base64:

const reader = new FileReader();
reader.onload = () => {
  const base64String = reader.result;
  // base64String is the complete data URI
};
reader.readAsDataURL(file);

In Node.js, the conversion uses the Buffer class:

const fs = require('fs');
const file = fs.readFileSync('image.png');
const base64 = file.toString('base64');
const dataUri = `data:image/png;base64,${base64}`;

Both approaches produce the same result, but for quick one-off conversions, an online tool is far more convenient.

Best Practices Summary

  1. Keep it small — only embed images under 4-5 KB. Above that threshold, use a separate file with cache headers.
  2. Prefer SVG — SVG files are already text-based and compress extremely well. They often do not even need base64 encoding; you can embed raw SVG XML directly in a data URI using percent-encoding.
  3. Compress first — optimize your image (using tools like TinyPNG, SVGO, or Squoosh) before converting to base64. A smaller input produces a smaller base64 string.
  4. Test your CSP — ensure your Content Security Policy allows data: in the relevant source directives.
  5. Measure the impact — use Lighthouse or WebPageTest to compare performance with and without base64 embedding. Real measurements beat rules of thumb.

Convert Your Images with PulpMiner

PulpMiner's free Base64 Image converter handles the conversion instantly in your browser. Drag and drop an image file, and the tool outputs the complete data URI ready to paste into your HTML or CSS. It supports PNG, JPEG, GIF, WebP, and SVG formats.

Need to extract data from websites?

PulpMiner turns any webpage into structured JSON data. No scraping code needed.

Try PulpMiner Free

No credit card required