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:
readAsDataURLis asynchronous — the result only exists inside theonloadcallback (or afterawaiting a promise wrapper).- If you need to resize or compress first, draw the image to a
<canvas>and usecanvas.toDataURL('image/jpeg', 0.8)— that returns a data URI too. - The data URI prefix tells the consumer what the bytes are. Keep it for HTML/CSS/JSON; strip it only when an API explicitly wants the raw Base64 body.
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:
- Open the file in binary mode (
'rb'). Reading as text is the #1 cause of corrupted output. b64encodereturnsbytes; call.decode('ascii')when you need astrfor JSON.- For URLs instead of files:
base64.b64encode(requests.get(url).content).decode(). - If the consumer expects URL-safe Base64 (no
+/), usebase64.urlsafe_b64encode.
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:
file_get_contentsworks on URLs too, but only ifallow_url_fopenis on — on shared hosting it sometimes isn't. cURL is the portable alternative.- When echoing into HTML, the Base64 body itself is safe (it contains no HTML-special characters apart from
+and/), but keep quotes around the attribute value. - To decode the other direction:
base64_decode($b64, true)— thetruemakes it strict and reject malformed input.
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:
- Get the image as binary data — a Read/Write Files from Disk node, or an HTTP Request node with Response → Format: File.
- 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-off, no code: the in-browser converter — drag, copy, done, and the image never leaves your machine.
- In a web app: FileReader (JavaScript section above).
- Backend / scripts: your language's one-liner (Python, PHP, Java, Node above).
- Automation: n8n Code node, as above.
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.