How to Encode an Image to Base64

Convert images to Base64 strings for embedding in HTML, CSS, or JSON. Learn the process, supported formats, and when image-to-Base64 makes sense.

Encoding

Detailed Explanation

Encoding an image to Base64 means reading the raw binary bytes of an image file (PNG, JPEG, GIF, SVG, WebP, etc.) and converting them into a Base64 text string. This string can then be embedded directly into HTML, CSS, or JSON without requiring a separate HTTP request to load the image.

In the browser with JavaScript:

const input = document.querySelector('input[type="file"]');
input.addEventListener("change", () => {
  const reader = new FileReader();
  reader.onload = () => {
    const base64String = reader.result;
    // result is a data URI like "data:image/png;base64,iVBOR..."
  };
  reader.readAsDataURL(input.files[0]);
});

The FileReader.readAsDataURL() method is the easiest browser-side approach. It returns a complete data URI including the MIME type prefix, ready to use in an <img> tag's src attribute.

In Node.js:

const fs = require("fs");
const imageBuffer = fs.readFileSync("photo.png");
const base64String = imageBuffer.toString("base64");
const dataUri = `data:image/png;base64,${base64String}`;

When to use image-to-Base64:

  • Small icons and logos under 10KB, where eliminating an HTTP request improves performance.
  • Email HTML templates, where external image links may be blocked by email clients.
  • Single-file HTML exports or documentation that must be self-contained.

When NOT to use it:

  • Large images. A 500KB JPEG becomes approximately 667KB as Base64, and the browser cannot cache it independently.
  • Images that appear on multiple pages. A separate file served with proper cache headers is far more efficient.
  • Responsive images where you need multiple sizes. Base64 does not support srcset.

The 33% size increase from Base64 encoding is partially offset when the HTML/CSS file is served with gzip or Brotli compression, which compresses Base64 text effectively. However, the browser must still decode the full Base64 string before rendering.

Use Case

Embedding small UI icons directly into a CSS stylesheet as data URIs to reduce the number of HTTP requests on a performance-critical landing page.

Try It — Base64 Encoder

Open full tool