Skip to content
Images 6 min read

Image to Base64: Inline Images in HTML, CSS, and JavaScript

Learn when to embed images as Base64 data URIs, how to convert images to Base64 in the browser and Node.js, the trade-offs for performance, and CSS background data URIs.

ToolsVito Team

What Is a Data URI?

A data URI embeds the file content directly in the HTML or CSS as a Base64-encoded string, eliminating the need for a separate HTTP request:

<!-- External image — 1 HTTP request -->
<img src="/icons/check.svg" alt="Check">

<!-- Inline data URI — 0 HTTP requests -->
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCI+..." alt="Check">

Converting Images to Base64 in the Browser

// From a File object (e.g., file input)
function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result); // "data:image/png;base64,..."
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

const input = document.querySelector('input[type="file"]');
const dataUrl = await fileToBase64(input.files[0]);

// From a canvas element
const canvas = document.querySelector("canvas");
const dataUrl = canvas.toDataURL("image/png");         // PNG
const dataUrl = canvas.toDataURL("image/jpeg", 0.85);  // JPEG at quality 0.85
const dataUrl = canvas.toDataURL("image/webp", 0.85);  // WebP

Converting Images to Base64 in Node.js

import fs from "fs";

// Read file and convert to Base64
const imageBuffer = fs.readFileSync("image.png");
const base64 = imageBuffer.toString("base64");
const dataUri = `data:image/png;base64,${base64}`;

// Detect MIME type from extension
import path from "path";
const ext = path.extname("image.png").slice(1); // "png"
const mimeMap = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp", svg: "image/svg+xml", gif: "image/gif" };
const mime = mimeMap[ext] || "application/octet-stream";

SVG in CSS as Data URI

/* SVG can be embedded in CSS without Base64 encoding (URL encoding is enough) */
.icon {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%23000' d='M12 2L2 7l10 5 10-5-10-5z'/%3E%3C/svg%3E");
  /* Note: # in colors must be encoded as %23 */
}

When Data URIs Make Sense

Good use cases:

  • Small icons (<2 KB) used on every page — saves HTTP round-trips
  • Critical above-the-fold images — embeds in HTML, no render-blocking request
  • Email templates — many email clients block external images by default
  • Single-file exports (HTML reports, offline apps)

Avoid for:

  • Large images — 33% size overhead + no browser caching = net loss
  • Images used on multiple pages — external files are cached across page loads
  • Frequently changing images — invalidates the entire HTML cache on every change

Decoding a Data URI

// Extract Base64 data from a data URI
const dataUri = "data:image/png;base64,iVBORw0K...";
const [header, base64] = dataUri.split(",");
const mime = header.match(/data:([^;]+)/)[1];  // "image/png"

// In Node.js — convert back to buffer
const buffer = Buffer.from(base64, "base64");
fs.writeFileSync("recovered.png", buffer);

Convert Images to Base64 Instantly

Use ToolsVito's Image to Base64 tool to convert any image to a data URI or extract an image from a data URI — in your browser.

Try it now — free, runs in your browser

Image to Base64

Image → Data URI & back