A Base64 image URL is a data: URL that contains an image’s MIME type and its Base64-encoded bytes:
data:<image MIME type>;base64,<encoded image bytes>
For example, a PNG begins with data:image/png;base64, and a JPEG with data:image/jpeg;base64,. The comma is required because it separates the header from the encoded payload. Use the method that matches your source: FileReader.readAsDataURL() for a browser file or Blob, base64 for a local file in a shell, and canvas.toDataURL() for pixels already drawn on a canvas.
| # | Preview | Product | Price | |
|---|---|---|---|---|
| 1 |
|
SKLaserDesign Two-Sided Medical Coding Carousel Rotating Book Stand - Made in the USA | $89.99 | Buy on Amazon |
What a Base64 image URL contains
The complete value has three parts:
data:identifies the data URL scheme.- The media type, such as
image/png,image/jpeg, orimage/webp, describes the bytes that follow. ;base64,declares Base64 encoding and places the payload after the comma.
A full value looks like data:image/png;base64,iVBORw0KGgoAAAANSUhEUg.... A bare Base64 string is only the characters after the comma. These are different inputs: an <img src> normally needs the complete data URL, while an API that documents a “Base64 payload” may require only the encoded characters.
MDN documents the syntax and browser behavior in its data URL reference; the scheme itself is specified by RFC 2397.
Recommended Free Tools
#1 Best Overall
- New design has wider shelves and supports, increasing stability for wide books. Shelf width is now 14.5".
- Easily holds two large medical coding books.
- Made in the USA - Minor assembly required.
Method 1: Convert a user-selected file in the browser
When an HTML file input provides a File, FileReader.readAsDataURL() reads the bytes and returns the complete URL in reader.result. This is the most direct approach for an upload form.
Complete working example
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Image to Base64 data URL</title>
<input id="imageFile" type="file" accept="image/*">
<textarea id="output" rows="8" cols="80" readonly></textarea>
<img id="preview" alt="Preview" style="display:block;max-width:400px;margin-top:1rem">
<script>
const input = document.querySelector('#imageFile');
const output = document.querySelector('#output');
const preview = document.querySelector('#preview');
input.addEventListener('change', () => {
const file = input.files[0];
if (!file) return;
if (!file.type.startsWith('image/')) {
output.value = 'Please select an image file.';
preview.removeAttribute('src');
return;
}
const reader = new FileReader();
reader.addEventListener('load', () => {
const imageDataUrl = reader.result; // header plus Base64 payload
output.value = imageDataUrl;
preview.src = imageDataUrl;
});
reader.addEventListener('error', () => {
output.value = 'The browser could not read this file.';
});
reader.readAsDataURL(file);
});
</script>
Open the page, choose an image, and copy the value from the text area. The result includes the correct type reported by the file (for example, image/png). Keep that entire string when assigning it to src or another field that accepts a data URL. The API and event behavior are described in MDN’s FileReader.readAsDataURL() documentation.
Getting only the payload
If a service explicitly requests bare Base64, remove the declaration once, rather than removing arbitrary characters:
const fullUrl = reader.result;
const comma = fullUrl.indexOf(',');
const payload = comma >= 0 ? fullUrl.slice(comma + 1) : fullUrl;
Do not strip the prefix when the destination expects an image URL; doing so produces a string that an <img> element cannot interpret by itself.
Method 2: Encode an image from Linux or macOS
The shell method encodes the file’s bytes and prepends a header. Do not use a text command such as echo on an image; encode the binary file itself.
PNG example
printf 'data:image/png;base64,'
base64 image.png
Some implementations wrap long output onto multiple lines. If the receiving field requires one uninterrupted URL, use that system’s no-wrap option or remove line breaks while leaving every Base64 character unchanged. A portable single-line pattern using common Unix tools is:
{ printf 'data:image/png;base64,'; base64 image.png | tr -d 'n'; } > image-data-url.txt
Check that the file starts with data:image/png;base64,. Change the MIME type and filename together for JPEG or WebP:
{ printf 'data:image/jpeg;base64,'; base64 photo.jpg | tr -d 'n'; } > photo-data-url.txt
{ printf 'data:image/webp;base64,'; base64 graphic.webp | tr -d 'n'; } > graphic-data-url.txt
On systems whose base64 command supports it, base64 -w 0 image.png (GNU) or base64 -b 0 image.png (some BSD variants) prevents wrapping. Check your local command’s help text because options differ by operating system. MDN’s data URL guide explains why the header and comma must be retained.
Method 3: Create a data URL from canvas pixels
For an image generated or edited in an HTML canvas, call toDataURL():
const canvas = document.querySelector('canvas');
const pngUrl = canvas.toDataURL(); // PNG by default
const jpegUrl = canvas.toDataURL('image/jpeg', 0.85);
const webpUrl = canvas.toDataURL('image/webp', 0.8);
console.log(pngUrl);
Browsers must support PNG. JPEG and WebP support is common, but a requested type that the browser does not support falls back to PNG, so inspect the returned prefix before relying on a format. The canvas API details and format behavior are in MDN’s HTMLCanvasElement.toDataURL() reference.
Large-canvas warning
toDataURL() constructs the complete image as an in-memory string. For a large canvas, that can consume substantial memory and hit a URL or field limit. MDN recommends toBlob() plus URL.createObjectURL() for larger images:
canvas.toBlob(blob => {
if (!blob) throw new Error('Canvas export failed');
const objectUrl = URL.createObjectURL(blob);
document.querySelector('#preview').src = objectUrl;
// URL.revokeObjectURL(objectUrl) when the preview is no longer needed.
}, 'image/png');
An object URL is not a Base64 data URL, but it avoids copying the whole image into a JavaScript string. Convert the Blob with FileReader only when the receiving interface specifically requires Base64.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Choosing the right approach
| Source | Best method | Result | Main consideration |
|---|---|---|---|
| File input, File, or Blob | FileReader.readAsDataURL() |
Complete data URL | Use the returned MIME type and keep the prefix when an image URL is required. |
| Existing local file in a shell | base64 plus a header |
Complete data URL or payload | Prevent line wrapping if one line is required. |
| Canvas content | toDataURL(type, quality) |
Complete data URL | PNG is the default; large images may need toBlob(). |
Before sending the value, verify what the destination accepts: a complete data URL, a bare payload, an object URL, or a normal hosted URL. A data URL is text encoding, not compression. Base64 generally makes the representation longer, so resize or compress the source separately when transfer size matters. RFC 4648 defines Base64 as an encoding, not an encryption method.
Using the URL in HTML, CSS, and JavaScript
HTML image
<img src="data:image/png;base64,iVBORw0KGgo..." alt="Embedded image">
CSS background
.logo {
background-image: url("data:image/svg+xml;base64,PHN2Zy...");
}
JavaScript assignment
document.querySelector('#preview').src = imageDataUrl;
For generated files, emails, or JSON requests, confirm that the target’s size and security policies allow data URLs. Inline images can simplify a small self-contained document, but a normal URL is usually easier to cache, update, and deliver for a large or frequently reused asset.
Why an image data URL fails to display
The comma is missing
Correct: data:image/png;base64,AAAA.... Without the comma, the parser cannot separate metadata from payload.
The MIME type is wrong
The declaration must describe the actual bytes. A JPEG encoded with image/png may fail or be interpreted unpredictably. Use file.type from a browser file when trustworthy, or identify the format before constructing a shell header.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →The ;base64 marker is absent
data:image/png,AAAA... describes non-Base64 data. Include ;base64, for a Base64 payload.
Only the payload was supplied
If the string starts with characters such as iVBOR but not data:, prepend the correct header or change the receiving API field to the one intended for bare Base64.
Line breaks or altered characters were introduced
Wrapped shell output, copied whitespace, URL decoding, or JSON escaping can corrupt a payload. Generate one line, preserve the Base64 alphabet and padding, and send it as the documented field value.
The canvas is tainted
If canvas pixels came from a cross-origin image without appropriate CORS permission, the browser can block export for security reasons. Host the image with suitable CORS headers or use same-origin content; do not attempt to bypass the browser’s protection.
The image is too large for the destination
Browsers are not required to support one universal maximum data-URL length; limits vary by implementation and can change. An API, database column, HTML attribute, email client, or proxy may impose a smaller limit. Reduce dimensions, choose an efficient format, upload the file normally, or use an object URL for a local preview.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Security and origin considerations
Base64 is neither encryption nor sanitization. Treat a data URL built from untrusted input as untrusted content. Modern browsers give data URLs unique opaque origins, and MDN notes that top-level navigation to data URLs is blocked in modern browsers. Data URLs have also been used in phishing, so do not navigate users to arbitrary values or place attacker-controlled strings into HTML without proper validation and escaping. If your application accepts uploads, validate file type and size on the server as well as in the browser.
Or skip the browser setup
If your real goal is to obtain an image of a web page rather than encode an existing local image, ScreenshotNeo returns a PNG, JPEG, WebP, or PDF from one GET request. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
See the parameter reference in the ScreenshotNeo documentation. The same request can return an image you then convert to Base64 locally if a downstream field requires a data URL:
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →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)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const bytes = Buffer.from(await res.arrayBuffer());
ScreenshotNeo includes full-page capture, element selection, device and viewport controls, retina scale, custom CSS and JavaScript, waits, request blocking, headers and cookies, geolocation, resizing, caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage data, and an OpenAPI specification. Every feature is on every plan: 1,000 shots per month are free with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Practical size and performance guidance
- Prefer a normal hosted image when the asset is large, reused, or independently cacheable.
- Use a data URL for small icons, self-contained prototypes, generated previews, or a document that must travel as one text value.
- Remember that Base64 increases transfer and storage size; compression must happen before encoding.
- For canvas output, use a quality setting for lossy JPEG/WebP and compare the resulting prefix and visual quality.
- For repeated previews, keep a Blob object URL and revoke it when finished instead of repeatedly creating huge strings.
FAQ
Can I use a Base64 image URL in an <img> tag?
Yes. Set src to the complete value beginning with data:image/...;base64,, not to the payload alone.
How do I know whether an API wants the prefix?
Check its field definition. “Data URL” or “image URL” means keep the declaration; “Base64-encoded bytes” or “Base64 payload” usually means send only the characters after the comma.
Is Base64 suitable for storing every image in a database?
Usually not for large or frequently accessed images. The encoding adds overhead and can make caching and streaming less convenient; store the binary object or a hosted URL when those properties matter.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsFrequently Asked Questions
Does converting an image to Base64 change its visual quality?
Encoding alone does not change the bytes or visual quality. Quality changes only if you resize or recompress the image before encoding, such as exporting a canvas as JPEG with a lower quality value.
Can a data URL be used as a security measure?
No. Base64 is reversible encoding, not encryption, authentication, or input sanitization. Validate and protect untrusted content separately.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

