โ† Back to Blog

How to Encode Images to Base64

2026-04-07 ยท 5 min read

Why Convert Images to Base64

Converting images to Base64 strings has several practical uses: embedding images directly in HTML or CSS to reduce HTTP requests; transmitting image data through JSON APIs; storing and processing images in environments without filesystem access; and creating self-contained single-file HTML pages with all images embedded as Base64.

This technique is especially suitable for small icons (favicons, button icons, decorative elements) that are small in size and won't significantly increase page size when embedded as Base64. For large images, using URL references is still recommended to maintain browser caching benefits.

Converting Images Using Online Tools

The simplest approach is using an online Base64 image converter. Simply upload an image file, and the tool will automatically read the image's binary data, perform Base64 encoding, and generate a complete Data URI string (including the MIME type prefix). Tools usually also provide instant preview and one-click copy functionality.

When using online tools, it's recommended to process image assets that don't contain sensitive information. For photos with personal privacy, use local methods (command line or code) for conversion to avoid uploading images to third-party servers.

Converting in the Browser with JavaScript

// ๆ–นๆณ•1๏ผšไฝฟ็”จ FileReader API
// Method 1: Using FileReader API
function imageToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => resolve(e.target.result); // ๅฎŒๆ•ด Data URI
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

// ๆ–นๆณ•2๏ผšไฝฟ็”จ Canvas API๏ผˆๅฏๅŒๆ—ถๅŽ‹็ผฉ/่ฝฌๆ ผๅผ๏ผ‰
// Method 2: Using Canvas API (can also compress/convert format)
function imageToBase64WithCanvas(file, format = 'image/jpeg', quality = 0.8) {
  return new Promise((resolve) => {
    const img = new Image();
    const url = URL.createObjectURL(file);
    img.onload = () => {
      const canvas = document.createElement('canvas');
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0);
      URL.revokeObjectURL(url);
      resolve(canvas.toDataURL(format, quality));
    };
    img.src = url;
  });
}

Converting Images in Python

import base64
import mimetypes
from pathlib import Path

def image_to_base64(image_path):
    """ๅฐ†ๅ›พ็‰‡ๆ–‡ไปถ่ฝฌๆขไธบ Data URI ๆ ผๅผ็š„ Base64 ๅญ—็ฌฆไธฒ"""
    path = Path(image_path)
    mime_type, _ = mimetypes.guess_type(image_path)
    if mime_type is None:
        mime_type = 'application/octet-stream'

    with open(path, 'rb') as f:
        encoded = base64.b64encode(f.read()).decode('ascii')

    return f"data:{mime_type};base64,{encoded}"

# ไฝฟ็”จ็คบไพ‹ / Usage
data_uri = image_to_base64('logo.png')
print(data_uri[:60])  # ้ข„่งˆๅ‰60ๅญ—็ฌฆ

# ๅœจ HTML ไธญไฝฟ็”จ / Use in HTML
html = f''

Converting Images in Node.js

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

function imageToBase64(imagePath) {
  const ext = path.extname(imagePath).toLowerCase();
  const mimeTypes = {
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.gif': 'image/gif',
    '.webp': 'image/webp',
    '.svg': 'image/svg+xml',
  };
  const mimeType = mimeTypes[ext] || 'application/octet-stream';
  const data = fs.readFileSync(imagePath);
  const base64 = data.toString('base64');
  return `data:${mimeType};base64,${base64}`;
}

const dataURI = imageToBase64('./images/banner.jpg');
console.log(`Image size: ${dataURI.length} chars`);

Using Base64 Images in HTML and CSS

After getting the Data URI, it can be used in multiple scenarios. In HTML img tags: <img src="data:image/png;base64,..." alt="Image">. In CSS background-image: background-image: url('data:image/png;base64,...'). In CSS content property (pseudo-elements): content: url('data:image/png;base64,...').

Data URIs can also be used in email templates, but note that some email clients (like Gmail) may filter or block Data URI display. For email images, using CID (Content-ID) to reference inline attachments, or using external URLs, is generally more reliable.

Performance Considerations

While Base64 image embedding reduces HTTP requests, it has costs too. First, Base64 encoding increases image size by approximately 33%. Second, browsers cannot cache embedded Base64 images separately โ€” every page load requires re-parsing the entire document, whereas URL-referenced images can be cached separately on disk.

Rule of thumb: for images smaller than 5KB (like favicons, small icons), Base64 embedding is appropriate. For 5โ€“20KB images, weigh the tradeoffs for your specific scenario. For images larger than 20KB, URL references are strongly recommended. Modern web build tools (like Webpack, Vite) typically have threshold configurations to automatically decide whether to convert images to Base64.

Batch Converting Multiple Images

import base64
import json
from pathlib import Path

def batch_convert_to_base64(image_dir, output_json):
    """ๆ‰น้‡ๅฐ†็›ฎๅฝ•ไธญๆ‰€ๆœ‰ๅ›พ็‰‡่ฝฌไธบ Base64 ๅนถ่พ“ๅ‡บ JSON"""
    result = {}
    image_extensions = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}

    for img_path in Path(image_dir).iterdir():
        if img_path.suffix.lower() in image_extensions:
            with open(img_path, 'rb') as f:
                encoded = base64.b64encode(f.read()).decode('ascii')
            result[img_path.name] = encoded

    with open(output_json, 'w') as f:
        json.dump(result, f, indent=2)

    print(f"Converted {len(result)} images")

batch_convert_to_base64('./icons', './icons_base64.json')

Try the free tool now

Use Free Tool โ†’