ScreenshotNeo

BlogHow-to

Convert an Image to Base64 Online

Convert an image to a Base64 data URL in your browser, extract the raw payload, automate it with code, and avoid common encoding errors.

By the ScreenshotNeo team1 October 20268 min read

To convert an image to Base64 online, choose the file in a browser and read it with FileReader.readAsDataURL(). The result is a complete data URL such as data:image/png;base64,iVBORw0KGgo.... If the destination asks for only Base64, remove everything before and including the first comma.

Base64 is an ASCII representation of binary bytes. It does not describe the image format by itself; the media type in a data URL, such as image/png or image/jpeg, supplies that information. See MDN’s data URL reference.

1. Convert an image in your browser

This standalone page performs the conversion locally in the browser. It provides both output forms:

  • Complete data URL: use it where a field expects an image URL.
  • Raw Base64 payload: use it where an API explicitly asks for Base64 data.
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Image to Base64 converter</title>
<label>Choose an image: <input id="file" type="file" accept="image/*"></label>
<p>Data URL</p>
<textarea id="dataUrl" rows="8" cols="100" readonly></textarea>
<button id="copyDataUrl" type="button">Copy data URL</button>
<p>Raw Base64 payload</p>
<textarea id="base64" rows="8" cols="100" readonly></textarea>
<button id="copyBase64" type="button">Copy raw Base64</button>
<p id="status" role="status"></p>
<script>
const fileInput = document.querySelector('#file');
const dataUrlOutput = document.querySelector('#dataUrl');
const base64Output = document.querySelector('#base64');
const status = document.querySelector('#status');

fileInput.addEventListener('change', () => {
  const file = fileInput.files[0];
  if (!file) return;
  if (!file.type.startsWith('image/')) {
    status.textContent = 'Choose an image file.';
    return;
  }

  const reader = new FileReader();
  reader.addEventListener('load', () => {
    const dataUrl = String(reader.result);
    const comma = dataUrl.indexOf(',');
    dataUrlOutput.value = dataUrl;
    base64Output.value = comma === -1 ? dataUrl : dataUrl.slice(comma + 1);
    status.textContent = `${file.name}: ${file.size.toLocaleString()} bytes`;
  });
  reader.addEventListener('error', () => {
    status.textContent = 'The browser could not read this file.';
  });
  reader.readAsDataURL(file);
});

async function copyValue(output) {
  if (!output.value) return;
  await navigator.clipboard.writeText(output.value);
  status.textContent = 'Copied.';
}

document.querySelector('#copyDataUrl').addEventListener('click', () => copyValue(dataUrlOutput));
document.querySelector('#copyBase64').addEventListener('click', () => copyValue(base64Output));
</script>
</html>

readAsDataURL() returns a data URL when the read finishes. MDN notes that you must remove the declaration before decoding or submitting only the Base64 payload: FileReader.readAsDataURL().

What the comma means

data:[<media-type>][;base64],<data>

For data:image/jpeg;base64,/9j/4AAQ..., the prefix is data:image/jpeg;base64, and the payload starts at /9j/4AAQ.... Split on the first comma rather than assuming every file is PNG or JPEG.

2. Choose the correct output for your destination

Destination Use Example
HTML image source Complete data URL <img src="data:image/png;base64,...">
CSS background Complete data URL background-image: url("data:image/svg+xml;base64,...")
API field named base64 Usually raw payload {"image":"iVBORw0..."}
API field named data_url or url Complete data URL {"url":"data:image/png;base64,..."}

Read the receiving API’s documentation. Sending a data URL where raw Base64 is expected commonly produces an invalid-character or decode error.

3. Command-line conversion

For a local file, the standard base64 utility creates the raw payload. Add the media type yourself when you need a data URL.

# Raw Base64 payload (GNU/Linux)
base64 -w 0 photo.png > photo.base64

# macOS and BSD systems (line wrapping disabled)
base64 photo.png | tr -d '\n' > photo.base64

# Build a PNG data URL
printf 'data:image/png;base64,' > photo.data-url
base64 -w 0 photo.png >> photo.data-url

Some implementations wrap output at fixed column widths. Remove newlines when the receiving field requires one uninterrupted string.

4. Convert with Python

from pathlib import Path
import base64

path = Path("photo.png")
payload = base64.b64encode(path.read_bytes()).decode("ascii")
data_url = f"data:image/png;base64,{payload}"

Path("photo.base64").write_text(payload, encoding="ascii")
Path("photo.data-url").write_text(data_url, encoding="ascii")
print(data_url[:80] + "...")

For a type other than PNG, change the media type to match the bytes. Python’s encoder does not inspect or convert image formats; it only encodes the file bytes.

5. Convert with Node.js

import { readFile, writeFile } from 'node:fs/promises';

const file = 'photo.jpg';
const bytes = await readFile(file);
const payload = bytes.toString('base64');
const dataUrl = `data:image/jpeg;base64,${payload}`;

await writeFile('photo.base64', payload, 'ascii');
await writeFile('photo.data-url', dataUrl, 'ascii');
console.log(dataUrl.slice(0, 80) + '...');

6. Convert with cURL when an API accepts an uploaded file

cURL itself does not provide a portable image-to-Base64 transformation. Generate the payload with your platform’s base64 command, then place it in the request body. For example:

PAYLOAD="$(base64 -w 0 photo.png)"
curl https://example.invalid/images \
  -H 'Content-Type: application/json' \
  --data "{\"image\":\"$PAYLOAD\"}"

For large files, avoid putting the value in a shell variable because command-line environments and operating systems impose size limits. Stream or upload the original file when the API supports multipart uploads.

7. Transform an image before encoding

Use a canvas when you need to resize, crop, or change the output format. HTMLCanvasElement.toDataURL() returns a data URL and defaults to PNG; supported formats can be requested. See MDN’s toDataURL() reference.

const image = new Image();
image.onload = () => {
  const canvas = document.createElement('canvas');
  const maxWidth = 1200;
  const scale = Math.min(1, maxWidth / image.naturalWidth);
  canvas.width = Math.round(image.naturalWidth * scale);
  canvas.height = Math.round(image.naturalHeight * scale);
  canvas.getContext('2d').drawImage(image, 0, 0, canvas.width, canvas.height);

  // JPEG quality is a number from 0 to 1.
  const dataUrl = canvas.toDataURL('image/jpeg', 0.85);
  console.log(dataUrl);
};
image.src = URL.createObjectURL(document.querySelector('#file').files[0]);

toDataURL() creates the entire encoded image as an in-memory string. MDN recommends considering toBlob() with an object URL for large images. If you draw an image from another origin, canvas security rules can also prevent export unless the resource permits it with appropriate CORS headers.

8. File size, memory, and data URL limits

  • Base64 increases the encoded representation’s size compared with the original binary bytes. Plan for a larger request or document.
  • Reading a file, creating a string, copying it to a textarea, and serializing JSON can each require additional memory.
  • Data URLs are convenient for small inline resources but become difficult to maintain in HTML, CSS, logs, and API payloads as they grow.
  • Browsers do not have one universal maximum data URL length. MDN reports current implementation limits of 512 MB for Chromium and Firefox and 2048 MB for Safari/WebKit; treat these as browser-specific limits, not a target size. See MDN’s data URL documentation.

For large images, prefer a normal file upload or object storage URL when the receiving system allows it. If you only need a preview, resize or compress before encoding.

9. Privacy and security considerations

A browser script can read a file selected by the user without automatically uploading it. An online converter may use a different architecture, so do not assume that a particular website processes files locally or deletes uploads unless its implementation and policy say so. The browser APIs alone do not establish an online service’s privacy practices.

Data URLs are treated by modern browsers as unique opaque origins. They have also been associated with phishing and other security issues, and modern browsers block top-level navigation to data URLs. Avoid placing untrusted data URLs in security-sensitive contexts, and validate MIME types and payloads on the server before processing them.

10. Troubleshooting

Symptom Cause Fix
Image does not display Missing or incorrect media-type prefix Use a complete value such as data:image/png;base64,... and verify the original format.
API says invalid Base64 The data:image/...;base64, declaration was included in a payload-only field Split at the first comma and submit only the text after it.
Decoder reports unexpected whitespace Command-line output wrapped across lines Disable wrapping or remove newline characters.
Output is empty No file was selected or FileReader failed Check input.files[0], listen for error, and try a readable local file.
Browser tab becomes slow A large data URL is held in several strings and controls Use toBlob(), stream an upload, resize the image, or process it server-side.
Canvas export throws a security error Pixels came from a cross-origin image without suitable CORS permission Serve the image with the required CORS headers or process the file without drawing it to canvas.
Colors or dimensions changed Canvas conversion re-encoded the image Use direct file encoding when no transformation is needed; choose the requested canvas format and quality deliberately.

11. Or skip the browser setup

If your real task is capturing a web page as an image or PDF before sending it to another system, ScreenshotNeo provides a website screenshot API and MCP server. Its one-call response can be PNG, JPEG, WebP, or PDF; see the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server lets AI agents use take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots.

Create a free ScreenshotNeo account and start with 1,000 screenshots per month without a card.

12. FAQ

Is Base64 encryption?

No. Base64 is an encoding that makes binary bytes representable as text. Anyone with the value can decode it.

Can I recover the original file?

Yes, if the complete payload is intact. Decode the Base64 bytes and save them with the correct file extension and media type.

Should I put images in HTML as data URLs?

For small, stable assets, this can be practical. For larger or frequently changed images, a normal URL or upload is usually easier to cache, update, and monitor.

Does converting to Base64 change image quality?

Direct Base64 encoding does not alter bytes or quality. Resizing, format conversion, or JPEG re-encoding can change quality before the encoding step.

Why does my Base64 string differ from another converter’s output?

Different source bytes produce different strings. A converter may also transform the image, change its format, add a data URL prefix, or include line breaks.