To put an image directly in HTML, convert it to a data URL: data:[media-type];base64,[encoded-data]. The complete value—including the data:image/png;base64, (or other media type) prefix—can be assigned to an image’s src attribute. In a browser, use FileReader.readAsDataURL() for a selected file or canvas.toDataURL() when the image already exists on a canvas.
What “Base64 image in HTML” actually means
Base64 is an encoding for binary bytes. HTML does not normally understand a bare encoded string as an image; it needs a data URL that declares both the media type and encoding. The general syntax is documented by MDN’s data URL reference and RFC 2397:
data:[media-type];base64,[encoded-data]
For example, a PNG might begin data:image/png;base64,, a JPEG data:image/jpeg;base64,, or a WebP data:image/webp;base64,. Keep that prefix when assigning the result to src. Remove everything through the first comma only when an API specifically asks for the bare Base64 payload.
Minimal HTML example
<img src="data:image/png;base64,iVBORw0KGgoAAA..." alt="Embedded image">
A data URL can also be used in CSS, such as background-image: url("data:image/svg+xml;base64,..."), but this article focuses on raster images in HTML and JavaScript.
#1 Best Overall
Method 1: Convert a selected local image with FileReader
Use FileReader.readAsDataURL(file) when the input is a local File or Blob. The operation is asynchronous. It does not return a string immediately; wait for the reader’s completion event, then read reader.result. MDN documents this behavior in its FileReader.readAsDataURL() reference.
Complete browser example
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Image to Base64 data URL</title>
<input id="imageInput" type="file" accept="image/*">
<img id="preview" alt="Selected image preview">
<textarea id="output" rows="8" cols="80" readonly></textarea>
<script>
const input = document.querySelector("#imageInput");
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 = "Choose an image file.";
return;
}
const reader = new FileReader();
reader.addEventListener("load", () => {
const dataUrl = reader.result;
preview.src = dataUrl;
output.value = dataUrl;
});
reader.addEventListener("error", () => {
output.value = "The file could not be read.";
});
reader.readAsDataURL(file);
});
</script>
After the user selects a file, reader.result is the complete data URL. It can be assigned directly to an <img>, stored in application state, or submitted to code that accepts a data URL.
Getting only the Base64 payload
If a service requires only encoded bytes, split at the first comma:
reader.addEventListener("load", () => {
const dataUrl = String(reader.result);
const base64Payload = dataUrl.slice(dataUrl.indexOf(",") + 1);
console.log(base64Payload);
});
Do not strip the prefix for normal HTML image embedding. Without the media-type declaration, the browser cannot treat the value as the same image source.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Validate and limit uploads
The accept attribute improves the file picker but is not a security boundary. Check file.type, enforce a size limit appropriate to your application, and validate files again on a server if they leave the browser. A malformed or unexpectedly large file can consume memory when converted to a string.
Rank #2
- HTML CSS Design and Build Web Sites
- Comes with secure packaging
- It can be a gift option
Method 2: Export a canvas image with toDataURL()
Use canvas.toDataURL() when an image has already been drawn, cropped, resized, or otherwise edited on a canvas. The method returns a data URL. PNG is the default and is required; browsers may support JPEG or WebP, and unsupported requested types fall back to PNG. The MDN toDataURL() reference describes the format and quality argument.
Canvas conversion example
const image = new Image();
image.onload = () => {
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
const context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
const pngDataUrl = canvas.toDataURL();
document.querySelector("#preview").src = pngDataUrl;
const jpegDataUrl = canvas.toDataURL("image/jpeg", 0.85);
console.log(jpegDataUrl);
};
image.src = "photo.jpg";
The JPEG quality value is a number from 0 to 1 for supported lossy formats; 0.85 requests a quality level, not a guaranteed file size or visual result. To detect format fallback, inspect the returned prefix:
const requested = canvas.toDataURL("image/webp", 0.8);
if (requested.startsWith("data:image/png")) {
console.log("WebP was not supported; the browser returned PNG.");
}
Canvas security: the origin-clean rule
If you draw an image from another origin without suitable cross-origin permission, the canvas becomes tainted. Calling toDataURL() can then throw a SecurityError. Host the image on the same origin, configure the image server’s CORS response correctly, and set image.crossOrigin before assigning src when your deployment supports that arrangement. A CORS header added only after the image has loaded cannot repair a tainted canvas.
Free tools Windows power users keep installed
One-click scans. No signup required.
Choosing the right conversion method
| Situation | Use | Why |
|---|---|---|
| User selected a local image and no editing is needed | FileReader.readAsDataURL() |
It supplies the complete data URL directly from a File or Blob. |
| Image is already drawn or must be cropped, resized, or composited | canvas.toDataURL() |
Canvas exports the transformed bitmap. |
| Very large image or long-lived asset | Separate image resource, or toBlob() plus an object URL |
Avoids keeping a large Base64 string in memory and preserves independent caching. |
Base64 data URLs are most useful for small, self-contained assets, prototypes, email-like generated markup, or values that must travel in one document. A conventional image URL is usually easier to cache, replace, inspect, and serve repeatedly.
Large images, memory, and better alternatives
toDataURL() materializes the entire encoded image as an in-memory string. MDN warns that very large images can hurt performance and may exceed URL-length limits, and says, “You should generally prefer toBlob() instead.” For a canvas result, use a Blob and an object URL:
Rank #3
canvas.toBlob((blob) => {
if (!blob) throw new Error("Canvas export failed");
const objectUrl = URL.createObjectURL(blob);
document.querySelector("#preview").src = objectUrl;
// When the image is no longer needed:
// URL.revokeObjectURL(objectUrl);
}, "image/png");
An object URL is not Base64 and is normally temporary, but it avoids copying the complete encoded image into a JavaScript string. For a permanent page asset, write the Blob to a file or serve the original image through a normal URL.
Common errors and fixes
The image shows a broken icon
Check that the value starts with the correct prefix, contains the comma, and has not been truncated by a database field, HTML sanitizer, or logging system. Assign the complete reader.result, not just an object or a Promise.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
The output is “undefined” or empty
readAsDataURL() finishes later. Put dependent code inside the load handler (or await a Promise wrapper); do not read reader.result immediately after starting the read.
The result is PNG when JPEG or WebP was requested
Inspect the returned prefix. The browser uses PNG when the requested type is unsupported. Choose a supported format or accept the PNG result.
SecurityError from canvas
The canvas is probably tainted by cross-origin content. Use same-origin assets or correctly configured CORS before drawing.
Rank #4
- Brand: Wiley
- Set of 2 Volumes
- A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
The page becomes slow or the HTML becomes enormous
Do not inline a large image as a data URL. Use a normal image URL, or use toBlob() and an object URL for a temporary preview. Keep only the data your consumer actually requires.
Recommended Free Tools
Wrong MIME type
Do not infer the type solely from a filename extension. For local files, inspect file.type; for canvas output, verify the returned prefix. The declared media type must match the bytes as closely as your browser and downstream consumer require.
Testing the generated HTML
- Open the page in a current browser and select a small PNG or JPEG.
- Confirm the preview renders and that the output begins with
data:image/. - Copy the complete value into a temporary
<img src="...">and verify it still renders. - Test an empty selection, a non-image file, a large image, and (for canvas) a cross-origin image.
- Check the actual prefix after requesting JPEG or WebP so a silent PNG fallback does not surprise your storage or upload code.
Or skip the browser setup
If your real goal is to capture a rendered web page rather than convert a local bitmap, ScreenshotNeo provides a website screenshot API and MCP server. Its one-call endpoint returns PNG, JPEG, WebP, or PDF:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo documentation for parameters. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.
The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is included on every plan. Create a free ScreenshotNeo account.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC 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 & 11Frequently asked questions
Can I paste a Base64 value directly into an HTML file?
Yes, if it is a complete data URL with a valid media-type prefix. A bare encoded payload is not a usable src value by itself.
Best Value
Does converting to Base64 improve image quality?
No. FileReader preserves the source bytes. Canvas export can change format, dimensions, or quality, so its result depends on the canvas operation and requested output type.
Is a data URL the same as an object URL?
No. A data URL contains encoded bytes in the string itself. An object URL points to a browser-managed Blob and is generally better for large temporary canvas results.
Frequently Asked Questions
Can a data URL be used in an email or generated document?
It can, provided the receiving renderer permits data URLs and the resulting document remains within its size and security limits. Test the target client; support and sanitization policies vary.
How do I decode the Base64 value later?
Split the data URL at its first comma, decode the second part with the API appropriate to your language, and use the media type from the declaration when writing the bytes back to a file.
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.

