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 problemsThe practical form of a Base64 image URL is data:<image MIME type>;base64,<encoded image bytes>. For example, a PNG starts with data:image/png;base64, and a JPEG with data:image/jpeg;base64,. The comma is required: it separates the data-URL header from the Base64 payload. Use the MIME type that matches the actual file format.
This guide shows how to create a complete data URL from a local image in a browser, export canvas content, encode a file on Linux or macOS, and diagnose images that do not display. It also explains when a bare Base64 string is required, why Base64 does not compress an image, and why large inline images can be a poor fit.
What a Base64 image URL contains
A data URL embeds bytes directly in a URL instead of pointing to a separate network resource. Its grammar is documented by MDN’s data-URL reference and RFC 2397:
data:<media-type>;base64,<encoded-payload>
- data: identifies the data-URL scheme.
- Media type: describes the bytes, such as
image/png,image/jpeg,image/gif, orimage/webp. - ;base64: tells the parser that the payload is Base64-encoded rather than ordinary URL characters.
- Comma: terminates the header. Everything after it is the encoded image data.
A complete value can be assigned directly to an image source:
#1 Best Overall
<img src="data:image/png;base64,iVBORw0KGgo..." alt="Embedded image">
A full data URL is not the same thing as a bare Base64 string. A FileReader result includes the data:image/...;base64, prefix. Remove that prefix only when the receiving API explicitly asks for the payload without a data-URL declaration.
Create a data URL from an image file in a browser
For a user-selected local image, use an <input type="file"> and FileReader.readAsDataURL(). The method accepts a File or Blob and returns the complete URL when reading finishes.
- Create a file input and, optionally, restrict the picker to images with
accept="image/*". - Read the first selected file with
reader.readAsDataURL(file). - Use
reader.resultafter theloadevent fires.
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Image to data URL</title>
<label>
Choose an image
<input id="imageFile" type="file" accept="image/*">
</label>
<img id="preview" alt="Selected image preview" hidden>
<textarea id="output" rows="8" cols="90" readonly></textarea>
<script>
const input = document.querySelector('#imageFile');
const preview = document.querySelector('#preview');
const output = document.querySelector('#output');
input.addEventListener('change', () => {
const file = input.files[0];
if (!file) return;
if (!file.type.startsWith('image/')) {
output.value = 'Please choose an image file.';
preview.hidden = true;
return;
}
const reader = new FileReader();
reader.addEventListener('load', () => {
const imageDataUrl = reader.result;
preview.src = imageDataUrl;
preview.hidden = false;
output.value = imageDataUrl;
});
reader.addEventListener('error', () => {
output.value = 'The browser could not read this file.';
});
reader.readAsDataURL(file);
});
</script>
</html>
The value in reader.result includes both the declaration and payload. Keep it intact for an img element, CSS background-image, or any API that accepts a data URL:
document.querySelector('#preview').src = reader.result;
document.body.style.backgroundImage = `url("${reader.result}")`;
Never assume that a file extension is the format. The browser’s file.type is a useful hint, but the data URL should describe the actual bytes. A PNG encoded as JPEG text will not become a JPEG; changing the prefix does not convert the file.
Free tools Windows power users keep installed
One-click scans. No signup required.
Get only the Base64 payload
Some APIs store the media type separately and require only characters after the comma. Split the result once, rather than removing a fixed number of characters:
const dataUrl = reader.result;
const comma = dataUrl.indexOf(',');
const mimeType = dataUrl.slice(5, comma); // e.g. image/png
const base64Payload = dataUrl.slice(comma + 1); // no header
Check the target specification before stripping anything. Sending a bare payload where a complete URL is expected produces a broken image; sending the prefix twice produces an invalid value.
Convert canvas content to a data URL
When the image is generated or edited in an HTML canvas, call canvas.toDataURL(). With no argument, browsers use PNG. You can request a MIME type and quality for formats that support it:
const canvas = document.querySelector('canvas');
const pngUrl = canvas.toDataURL();
const jpegUrl = canvas.toDataURL('image/jpeg', 0.85);
const webpUrl = canvas.toDataURL('image/webp', 0.85);
PNG support is required. JPEG and WebP are commonly supported, but support is not universal. If the requested type is unsupported, the browser falls back to PNG; inspect url.slice(0, url.indexOf(',')) when the format matters.
Canvas security restriction
If you draw an image loaded from another origin without appropriate CORS permission, the canvas can become “tainted.” Calling toDataURL() then throws a security exception. Serve the source with a suitable Access-Control-Allow-Origin response and set the image’s crossOrigin property before assigning its URL, or use same-origin assets.
Prefer blobs for large canvas output
toDataURL() constructs the entire encoded image as an in-memory string. MDN warns that this can consume substantial memory and run into URL-length limits for large images. Use toBlob() and URL.createObjectURL() for a preview or download instead:
Rank #3
canvas.toBlob((blob) => {
if (!blob) throw new Error('Canvas export failed');
const temporaryUrl = URL.createObjectURL(blob);
document.querySelector('#preview').src = temporaryUrl;
// Call URL.revokeObjectURL(temporaryUrl) when the preview is no longer needed.
}, 'image/png');
Encode an image from the command line
On Linux or macOS, encode the file’s bytes with base64, then prepend the correct header. Do not pass the image through a text conversion step.
printf 'data:image/png;base64,'
base64 image.png
Some implementations wrap long output onto multiple lines. If the destination requires one uninterrupted URL, use that implementation’s no-wrap option (for example, commonly base64 -w 0 image.png on GNU systems) or remove newline characters without changing any Base64 characters. A portable shell pattern that writes one line is:
Recommended Free Tools
{ printf 'data:image/png;base64,'; base64 image.png | tr -d 'n'; } > image-data-url.txt
For a JPEG, change the header to data:image/jpeg;base64,; for WebP, use data:image/webp;base64,. Verify the beginning of the output before placing it in HTML or JSON.
Use the URL in HTML, CSS, and JavaScript
HTML image
<img src="data:image/png;base64,..." alt="Description">
CSS background
.logo {
background-image: url("data:image/svg+xml;base64,...");
}
Quote the value when it contains characters that could be interpreted by CSS. For user-provided content, do not inject an untrusted data URL into HTML without validating its media type and output context.
JavaScript and JSON
const payload = {
image: reader.result // complete data URL
};
fetch('/api/upload', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(payload)
});
Confirm that the receiving endpoint accepts data URLs and that its request-body limits accommodate the encoded value.
Why a Base64 image may not display
- Missing comma: use
data:image/png;base64,AAAA..., notdata:image/png;base64AAAA.... - Wrong media type: match the bytes, such as
image/pngfor PNG. A prefix does not convert formats. - Missing
;base64marker: without it, the payload is parsed as non-Base64 data. - Line breaks or whitespace: wrapped shell output may fail in a field that expects one URL. Remove only formatting newlines.
- Truncated value: textarea, database, JSON, proxy, or URL limits may cut off the payload. Compare the beginning and end and inspect network errors.
- Using a bare payload as
src: prepend the complete header, or configure the API with the MIME type separately. - Tainted canvas: fix cross-origin image loading before calling
toDataURL(). - Unsupported canvas type: check the returned prefix because the browser may have fallen back to PNG.
- Escaping errors: preserve the string while embedding it in JSON, JavaScript, HTML, or CSS; escape the surrounding syntax, not Base64 characters arbitrarily.
Size, performance, and security trade-offs
Base64 is an encoding, not compression. As specified by RFC 4648, it represents binary bytes as text and generally makes the representation longer. Resize or recompress the image separately if size matters.
Data URLs can be useful for small icons, self-contained HTML, email templates, prototypes, and offline snippets because they eliminate a separate request. They are less suitable for photographs, repeated assets, or large canvases: the encoded string increases memory use, duplicates data wherever it is embedded, and can hit implementation-specific limits in browsers, servers, databases, or intermediary tools.
There is no single maximum data-URL length guaranteed by browsers. MDN documents browser-specific behavior and changing limits; treat limits as implementation details rather than a universal number. For large content, upload the file and reference an HTTPS URL, or use a blob/object URL for a temporary browser preview.
Data URLs are not encryption, authentication, or sanitization. Modern browsers treat them as unique opaque origins, and top-level navigation to data URLs is blocked in modern browsers. Because data URLs have been used in phishing and injection attacks, validate user-supplied values, restrict accepted media types, apply an appropriate Content Security Policy, and avoid navigating a browser to untrusted data URLs. Do not put secrets in an image string merely because it is difficult to read.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
If your real goal is to obtain an image of a web page rather than encode a local file, ScreenshotNeo returns a PNG, JPEG, WebP, or PDF from one GET request. It removes cookie/consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools to Claude, Cursor, and other MCP clients.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Use the API documentation at screenshotneo.com/docs/ for the current parameters. A complete cURL request is:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
The same request in Python:
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)
And in Node.js:
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(`Screenshot failed: ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());
require('node:fs').writeFileSync('shot.webp', image);
ScreenshotNeo supports full-page and element captures, device presets, custom viewports, retina scale, PDF controls, HTML/CSS-to-image, JavaScript and CSS, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, cache TTLs, signed links, asynchronous webhooks, bulk capture, usage reporting, and an OpenAPI specification. Its parameter names are compatible with those used by other screenshot APIs, which can simplify migration. Every plan includes every feature: 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 choice checklist
- Use
FileReader.readAsDataURL()for a local browserFileorBlob. - Use
canvas.toDataURL()for small canvas exports; usetoBlob()for larger results. - Use shell
base64for a file-based workflow and add the matching media-type header. - Keep the prefix when the destination expects a data URL; strip it only when a bare payload is documented.
- Validate size, MIME type, and trust boundaries before accepting or displaying user-provided data URLs.
Frequently Asked Questions
Can I turn a Base64 string back into an image?
Yes. Add the correct data:image/...;base64, prefix when a complete data URL is required, or decode the payload to binary bytes and save it with the matching image extension.
Does changing image/png to image/jpeg convert the image?
No. The header only describes the bytes. Convert or recompress the image with an image-processing tool, then encode the resulting file.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Should I store a data URL in a database?
Only for small, infrequently used assets when the database and API limits are known. For larger or reused images, store the binary object and reference it by URL.
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.

