Image Base64 Encoding

2026-05-28·6 min read·Image

Base64 Encoding Principles

Base64 is a method of encoding binary data into ASCII strings, commonly used for transmitting binary data in text protocols. In web development, Base64-encoded images can be directly embedded in HTML, CSS, or JSON without additional HTTP requests. This technique is called "Data URI," with the format data:image/png;base64,iVBORw0KGgo....

Base64 encoding increases file size by approximately 33%, but in certain scenarios can significantly improve page loading performance. For small icons (less than 10KB), Base64 encoding reduces HTTP request overhead. For large images, the traditional URL approach is better for browser caching and parallel loading.

Encoding Implementation

// JavaScript image to Base64
function imageToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

// Canvas method (can be used for image compression)
function compressImage(file, maxWidth = 800, quality = 0.8) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const img = new Image();
      img.onload = () => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');

        const ratio = Math.min(maxWidth / img.width, 1);
        canvas.width = img.width * ratio;
        canvas.height = img.height * ratio;

        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        resolve(canvas.toDataURL('image/jpeg', quality));
      };
      img.src = e.target.result;
    };
    reader.readAsDataURL(file);
  });
}

// Usage example
document.getElementById('file-input').addEventListener('change', async (e) => {
  const file = e.target.files[0];
  if (file) {
    const base64 = await imageToBase64(file);
    document.getElementById('preview').src = base64;
  }
});

Performance Impact and Best Practices

Base64-encoded images cannot be cached separately by browsers - they must be retransmitted every time the page loads. For frequently changing small icons (such as UI elements), Base64 is appropriate; for rarely changing image resources, the traditional URL approach is better for caching. A compromise is to merge small icons into CSS Sprites or use SVG icons.

Another consideration is SEO - search engines cannot index Base64-encoded images. Therefore, for images that need to be discovered by search engines (such as product images and article illustrations), traditional URL approach should be used.

Recommended Tools

Base64 Image Encoder is an online image Base64 conversion tool. Squoosh is Google's image compression and optimization tool supporting multiple formats. SVG Sprite Generator can merge multiple SVG icons. Sharp is a Node.js image processing library supporting efficient image operations.