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 });
}Test the result with the Base64 image validator.