How to Convert an Image to Base64 — in JavaScript, Python, PHP, Java & More

Base64 turns an image's binary bytes into plain text, so you can paste a picture straight into HTML, CSS, JSON or an API payload. Below is a working snippet for every major language — plus the gotcha that most bite people in each one. And if you just need it done once, with no code at all: the in-browser converter does it in one drag & drop, privately, with nothing uploaded.

JavaScript — in the browser

The browser-native way is the FileReader API. Give it a File (from an <input type="file">, a drag & drop, or the clipboard) and it hands you a complete data URI:

// From a file input
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', () => {
  const reader = new FileReader();
  reader.onload = () => {
    const dataUri = reader.result;        // "data:image/png;base64,iVBORw0KGgo..."
    const base64  = dataUri.split(',')[1]; // raw base64 body only
    console.log(base64);
  };
  reader.readAsDataURL(input.files[0]);
});

From a paste event, grab the item that is an image:

document.addEventListener('paste', (e) => {
  const item = [...e.clipboardData.items].find(i => i.type.startsWith('image/'));
  if (item) {
    const reader = new FileReader();
    reader.onload = () => useImage(reader.result);
    reader.readAsDataURL(item.getAsFile());
  }
});

Gotchas:

Node.js

const fs = require('fs');

const b64 = fs.readFileSync('image.png').toString('base64');
const dataUri = `data:image/png;base64,${b64}`;

Gotcha: prefer readFileSync's returned Buffer over readFile + string conversions — never read the file as UTF-8 text first, that corrupts binary data. For remote images, fetch(url) then Buffer.from(await res.arrayBuffer()).toString('base64').

Python

import base64

with open('image.png', 'rb') as f:          # 'rb' — binary mode, not text
    b64 = base64.b64encode(f.read()).decode('ascii')

data_uri = f'data:image/png;base64,{b64}'

Gotchas:

PHP

<?php
$b64 = base64_encode(file_get_contents('image.jpg'));

// ready to print into an <img> tag:
echo '<img src="data:image/jpeg;base64,' . $b64 . '">';

Gotchas:

Java

import java.nio.file.*;
import java.util.Base64;

byte[] bytes = Files.readAllBytes(Paths.get("image.png"));
String b64 = Base64.getEncoder().encodeToString(bytes);
String dataUri = "data:image/png;base64," + b64;

Gotcha: use java.util.Base64 (Java 8+). The old javax.xml.bind.DatatypeConverter.printBase64Binary() still works but lives in a module that was removed from the JDK in Java 11 — if you find it in old StackOverflow answers, that's why it doesn't compile anymore. For URL-safe output, swap in Base64.getUrlEncoder().

Linux / macOS command line

# one pasteable string (no line wrapping)
base64 -w0 image.png > image.b64

# full data URI in one line
echo "data:image/png;base64,$(base64 -w0 image.png)"

# decode the other direction
base64 -d image.b64 > restored.png

Gotcha: on macOS, the BSD base64 has no -w0 flag (it doesn't wrap by default), and decode is base64 -D (capital) instead of -d on older macOS versions; Linux (GNU coreutils) uses lowercase -d and wraps at 76 columns unless you pass -w0. A wrapped Base64 string pasted into JSON will break — that's what -w0 prevents.

n8n — convert an image to Base64 in a workflow

Automation platforms are where this question comes up most: you have an image as a file or a download, and an API node (OpenAI, a webhook, a database) that wants Base64. In n8n:

  1. Get the image as binary data — a Read/Write Files from Disk node, or an HTTP Request node with Response → Format: File.
  2. Add a Code node (JavaScript, like Node) and convert the binary property:
// n8n Code node — 'data' is the binary property name
const buf = await this.helpers.getBinaryDataBuffer(0, 'data');
return [{ json: { base64: buf.toString('base64') } }];

From there the Base64 string is a normal JSON field you can map into any downstream node. Gotcha: the property name in getBinaryDataBuffer(0, 'data') must match the binary output key of the previous node (usually data, sometimes file — check the node's output). The 0 is the item index.

Which approach should you pick?

One warning that applies everywhere: Base64 makes data about 33% larger. It's perfect for small icons, API payloads and fixtures; it's the wrong tool for large photos on public pages. Check the size first with the Base64 size calculator, and if you're inlining a PNG you can shrink it first with Compress PNG to Base64.

Frequently asked questions

How do I convert an image to Base64 in JavaScript?

Use a FileReader and call readAsDataURL(file) — the onload result is a complete data URI. Split at the first comma if you need only the Base64 body. See the JavaScript section for full code.

How do I convert an image to Base64 in Python?

base64.b64encode(open('img.png','rb').read()).decode('ascii') — binary mode is the part people forget. Full example in the Python section.

How do I encode an image to Base64 in PHP?

base64_encode(file_get_contents('img.jpg')). Details in the PHP section.

How do I convert an image to Base64 on the Linux command line?

base64 -w0 image.png — the -w0 disables line wrapping so the output is one pasteable string. Full examples in the command-line section.

How do I use an image as Base64 in n8n?

Read the image as binary data, then a Code node: (await this.helpers.getBinaryDataBuffer(0, 'data')).toString('base64'). Walkthrough in the n8n section.

Prefer not to write code at all? Use the in-browser Image to Base64 converter — it runs the same FileReader pipeline locally, with nothing uploaded.