Browser code reference
Base64 Image Code Examples
Small JavaScript patterns for encoding and decoding images in the browser. This page documents client-side code, not a hosted HTTP API.
File to Data URL
Use FileReader when the image comes from a browser file input.
function imageToDataUrl(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
}Data URL to Blob
Decode a Data URL into bytes when you need a downloadable Blob.
function dataUrlToBlob(dataUrl) {
const [header, payload] = dataUrl.split(',');
const mime = header.match(/data:([^;]+)/)[1];
const binary = atob(payload);
const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));
return new Blob([bytes], { type: mime });
}React file input
Keep the Data URL in component state for a local preview or request payload.
import { useState } from 'react';
export function ImagePicker() {
const [dataUrl, setDataUrl] = useState('');
function selectImage(event) {
const file = event.target.files[0];
if (!file?.type.startsWith('image/')) return;
const reader = new FileReader();
reader.onload = () => setDataUrl(String(reader.result));
reader.readAsDataURL(file);
}
return <>
<input type="file" accept="image/*" onChange={selectImage} />
{dataUrl && <img src={dataUrl} alt="Local preview" />}
</>;
}Node.js Buffer
Encode trusted local image bytes in Node.js. Keep the MIME type explicit.
import { readFile } from 'node:fs/promises';
const bytes = await readFile('./image.png');
const base64 = bytes.toString('base64');
const dataUrl = `data:image/png;base64,${base64}`;
const restored = Buffer.from(base64, 'base64');Python
Use the standard library to produce or decode Base64 without extra packages.
from base64 import b64decode, b64encode
from pathlib import Path
encoded = b64encode(Path("image.png").read_bytes()).decode("ascii")
data_url = f"data:image/png;base64,{encoded}"
Path("restored.png").write_bytes(b64decode(encoded, validate=True))URL-safe Base64
Replace the standard alphabet when the value must travel in a URL or filename.
function toUrlSafeBase64(base64, keepPadding = false) {
const result = base64.replace(/\+/g, '-').replace(/\//g, '_');
return keepPadding ? result : result.replace(/=+$/, '');
}
function fromUrlSafeBase64(value) {
const standard = value.replace(/-/g, '+').replace(/_/g, '/');
return standard.padEnd(Math.ceil(standard.length / 4) * 4, '=');
}OpenAI Chat Completions image input
Place the Data URL in an image_url content item. Send API requests from a trusted backend so the API key is not exposed.
const body = {
model: 'gpt-4.1-mini',
messages: [{
role: 'user',
content: [
{ type: 'text', text: 'Describe this image.' },
{ type: 'image_url', image_url: { url: dataUrl, detail: 'auto' } }
]
}]
};OpenAI Responses API image input
For the Responses API, use an input_image item alongside the text prompt.
const body = {
model: 'gpt-4.1-mini',
input: [{
role: 'user',
content: [
{ type: 'input_text', text: 'Describe this image.' },
{ type: 'input_image', image_url: dataUrl, detail: 'auto' }
]
}]
};Test the result with the Base64 image validator.