Home/Blog/Encode Image to Base64 in JavaScript
Base64 · JavaScript

Encode Image to Base64 in JavaScript

4 min readUpdated April 2026Developer Tools
Need to embed an image directly in HTML, CSS, or JSON? Base64 encoding converts any image to a text string you can use anywhere. Here's how to do it in the browser and Node.js.

Base64 Encoder / Decoder

Encode any file to Base64 instantly. Supports text and binary files. Runs in your browser.

Open Base64 Encoder / Decoder →

Browser — FileReader API

In the browser, use the FileReader API to convert a File or Blob to a Base64 data URL:

JavaScript — browser
function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload  = () => resolve(reader.result);
    reader.onerror = () => reject(reader.error);
  });
}

// Usage with a file input
const input = document.getElementById('fileInput');
input.addEventListener('change', async (e) => {
  const file = e.target.files[0];
  const base64 = await fileToBase64(file);
  // base64 = "data:image/png;base64,iVBORw0KGgo..."
  document.getElementById('preview').src = base64;
});

The result is a data URL — a string in the format data:image/png;base64,... that you can use directly as an img src or CSS background-image.

Browser — Canvas API (for already-loaded images)

JavaScript — convert HTMLImageElement to Base64
function imageToBase64(imgElement, format = 'image/png') {
  const canvas = document.createElement('canvas');
  canvas.width  = imgElement.naturalWidth;
  canvas.height = imgElement.naturalHeight;
  const ctx = canvas.getContext('2d');
  ctx.drawImage(imgElement, 0, 0);
  return canvas.toDataURL(format); // "data:image/png;base64,..."
}

const img = document.getElementById('myImage');
const base64 = imageToBase64(img, 'image/jpeg');
Note: Canvas toDataURL() fails with a security error if the image is cross-origin and doesn't have CORS headers. Use FileReader for user-uploaded files instead.

Node.js — Buffer

Node.js — read file and encode
import { readFileSync } from 'fs';

// Encode image file to Base64
function imageFileToBase64(filePath) {
  const buffer = readFileSync(filePath);
  return buffer.toString('base64');
}

const base64 = imageFileToBase64('./image.png');
// Use as data URL:
const dataUrl = `data:image/png;base64,${base64}`;

How to use Base64 images

HTML — inline image
<img src="data:image/png;base64,iVBORw0KGgo..." alt="Embedded image" />
CSS — background image
.icon {
  background-image: url('data:image/svg+xml;base64,PHN2ZyB4...');
  width: 24px;
  height: 24px;
}
JSON API — send image in JSON body
const payload = {
  userId: 123,
  avatar: base64String  // send without the data: prefix
};
await fetch('/api/upload', {
  method: 'POST',
  body: JSON.stringify(payload)
});

Frequently asked questions

Does Base64 encoding increase image file size?
Yes — Base64 increases size by approximately 33%. A 100 KB image becomes about 133 KB as Base64. Inline Base64 images also can't be cached by the browser separately. Use for small icons and critical above-the-fold images only.
How do I decode a Base64 image back to a file?
Strip the data URL prefix, decode from Base64, and write as binary. In Node.js: const buffer = Buffer.from(base64String, 'base64'); fs.writeFileSync('output.png', buffer);
What's the maximum size image I should Base64 encode?
Keep Base64 images under 5–10 KB for CSS backgrounds and inline HTML. Larger images are better served as separate files — they benefit from browser caching, HTTP/2 multiplexing, and CDN delivery.

Try it free — no sign-up needed

Runs entirely in your browser. Nothing uploaded, nothing stored.

Open Base64 Encoder / Decoder →

Related tools on tinybench.dev