X Xerobit

Base64 Image Encoding — Embed Images in HTML, CSS, and JSON

Base64 image encoding converts image files to text strings for embedding in HTML data URLs, CSS, and JSON APIs. Here's when to use it, how to encode images, and the performance...

Mian Ali Khalid · · 5 min read
Use the tool
Base64 Encoder / Decoder
Encode and decode Base64 strings and files. Client-side, safe for sensitive data.
Open Base64 Encoder / Decoder →

Base64 image encoding converts an image file’s binary data into a text string. The result can be embedded directly in HTML, CSS, JSON, or any text-based context — no separate image file needed.

Use the base64 encoder and decoder to encode images to base64 and create data URLs instantly.

The data URL format

A base64-encoded image in HTML uses a data URL:

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

Format: data:[MIME type];base64,[base64 data]

Common MIME types:

  • image/png — PNG images
  • image/jpeg — JPEG images
  • image/gif — GIF images
  • image/svg+xml — SVG (rarely base64-encoded; SVG is already text)
  • image/webp — WebP images
  • image/x-icon — ICO files (favicons)

Encoding images to base64

Using the online tool

  1. Open the Base64 Tool
  2. Click the file upload option
  3. Select or drag your image
  4. Copy the base64 output
  5. Construct the data URL: data:image/png;base64, + the copied string

JavaScript (browser)

// Encode a file (from file input):
function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);  // Returns full data URL
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
  });
}

// Usage with file input:
document.getElementById('fileInput').addEventListener('change', async (e) => {
  const file = e.target.files[0];
  const dataUrl = await fileToBase64(file);
  document.getElementById('preview').src = dataUrl;
  
  // Extract just the base64 part:
  const base64Only = dataUrl.split(',')[1];
});

// Encode from URL (fetch + encode):
async function urlToBase64(imageUrl) {
  const response = await fetch(imageUrl);
  const blob = await response.blob();
  const base64 = await new Promise(resolve => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(',')[1]);
    reader.readAsDataURL(blob);
  });
  return `data:${blob.type};base64,${base64}`;
}

Node.js

const fs = require('fs');
const path = require('path');

function imageToBase64DataUrl(imagePath) {
  const imageBuffer = fs.readFileSync(imagePath);
  const base64 = imageBuffer.toString('base64');
  const ext = path.extname(imagePath).slice(1).toLowerCase();
  const mimeTypes = { jpg: 'jpeg', jpeg: 'jpeg', png: 'png', gif: 'gif', webp: 'webp' };
  const mimeType = `image/${mimeTypes[ext] || ext}`;
  return `data:${mimeType};base64,${base64}`;
}

const dataUrl = imageToBase64DataUrl('./logo.png');
console.log(dataUrl);
// "data:image/png;base64,iVBORw0KGgoAAAANS..."

Python

import base64
import mimetypes

def image_to_base64_data_url(image_path):
    with open(image_path, 'rb') as f:
        image_data = f.read()
    
    base64_str = base64.b64encode(image_data).decode('utf-8')
    mime_type, _ = mimetypes.guess_type(image_path)
    return f"data:{mime_type};base64,{base64_str}"

data_url = image_to_base64_data_url('logo.png')
print(data_url[:50])  # data:image/png;base64,iVBORw0KGgoAAAANS...

Where base64 images are used

CSS (inline image references)

/* Small icon in CSS without a separate file request: */
.icon-check::before {
  content: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0i...');
}

/* Background image: */
.logo {
  background-image: url('data:image/png;base64,iVBORw0KGgo...');
  background-size: contain;
}

HTML email templates

Email clients often block external images by default (images behind a tracking pixel blocker). Base64-embedded images load without external requests:

<img src="data:image/png;base64,iVBORw0KGgo..." alt="Company Logo">

Caveat: This increases email size significantly. Some spam filters penalize large base64 blocks in emails. Use sparingly for critical images (logos) only.

JSON API responses

When an API returns image data alongside other JSON data:

{
  "user_id": "123",
  "name": "Alice",
  "avatar": "data:image/jpeg;base64,/9j/4AAQSkZJRgAB..."
}

Used when the client needs to display the image immediately without a separate request, or when the image is generated on the fly (QR codes, charts, thumbnails).

Favicons in HTML

Embed a favicon without a separate file request:

<link rel="icon" href="data:image/x-icon;base64,AAABAAE...">

Performance tradeoffs

Pros of base64 image embedding:

  • Eliminates one HTTP request per image
  • Images load with the page (no separate request)
  • Works offline (no external dependency)
  • Useful in email where external images are blocked

Cons:

  • Base64 encoding increases file size by ~33% (4/3 ratio)
  • Encoded images can’t be cached separately by the browser (the HTML page is cached, but not the image)
  • Large base64 blocks delay parsing of the HTML document
  • Not gzip-compressed as efficiently as binary

The break-even point: Images under 5–10KB benefit from base64 embedding (eliminates request overhead which may be larger than the size increase). Images over 10KB are usually better served as separate files that can be cached.

SVG images: don’t base64 encode them

SVG is already text (XML). For SVG in HTML/CSS, you can embed the SVG markup directly or use a data URL without base64 encoding:

<!-- Inline SVG (most efficient): -->
<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'...">

<!-- Or just use the SVG file: -->
<img src="icon.svg" alt="Icon">

For CSS background images, URL-encoded SVG is smaller than base64-encoded SVG:

/* URL-encoded SVG (smaller): */
background-image: url("data:image/svg+xml,%3Csvg...");

/* Base64 SVG (larger, unnecessary for text): */
background-image: url("data:image/svg+xml;base64,PHN2Zy...");

Related posts

Related tool

Base64 Encoder / Decoder

Encode and decode Base64 strings and files. Client-side, safe for sensitive data.

Written by Mian Ali Khalid. Part of the Encoding & Crypto pillar.