DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
Base64

How to Convert an Image to Base64 HTML Code (Data URLs, JavaScript, and Practical Limits)

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To put an image directly in HTML, convert it to a data URL: data:[media-type];base64,[encoded-data]. The easiest browser-native method for a selected image file is FileReader.readAsDataURL(); use canvas.toDataURL() when the image is already drawn on a canvas or needs editing first. Keep the complete data:image/...;base64, prefix when assigning the result to an <img src>.

What “Base64 image in HTML” actually means

Base64 is an encoding of binary bytes as text. HTML does not normally understand a bare Base64 payload as an image source, so the payload is wrapped in a data URL. The syntax is:

data:[media-type];base64,[encoded-data]

For a PNG, the beginning is usually data:image/png;base64,; JPEG uses data:image/jpeg;base64,, and WebP uses data:image/webp;base64,. The media type tells the browser what follows, while base64 identifies the encoding. RFC 2397 defines the data URL scheme, and MDN documents how browsers handle it.

Use the complete value like this:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUg..." alt="Example image">

Do not remove the prefix unless another API specifically asks for only the encoded payload. If you have a value beginning with data:, it is already ready for an image src, CSS url(), or another data-URL-compatible context.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Method 1: Convert a selected image file with FileReader

FileReader.readAsDataURL(file) is the direct choice when a user selects a local file through an <input type="file">. The read is asynchronous: readAsDataURL() starts the operation and returns no string. Read the result after the load event (or in the reader’s onload handler).

Complete browser example

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Image to Base64 data URL</title>
</head>
<body>
  <label>
    Choose an image:
    <input id="imageFile" type="file" accept="image/*">
  </label>
  <img id="preview" alt="Selected image preview">
  <textarea id="output" rows="8" cols="80" 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.";
        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>
</body>
</html>

When reading finishes, reader.result is a string containing both the declaration and the encoded bytes. This behavior is described in MDN’s FileReader.readAsDataURL() documentation.

Extract only the Base64 payload when required

Some upload or database interfaces request the payload without its declaration. Split at the first comma, rather than trying to remove a particular image type:

Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option
const dataUrl = reader.result;
const base64Payload = dataUrl.slice(dataUrl.indexOf(",") + 1);

Keep dataUrl for HTML image markup. Use base64Payload only when the receiving interface explicitly documents that format.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Method 2: Export an existing canvas image

Use HTMLCanvasElement.toDataURL() when the bitmap is already on a canvas—for example, after cropping, drawing, filtering, or compositing several images. The method returns a data URL. PNG is the default and is required. You can request another format and, for supported lossy formats, pass a quality value from 0 to 1.

PNG export

const canvas = document.querySelector("canvas");
const pngDataUrl = canvas.toDataURL();
document.querySelector("img").src = pngDataUrl;

JPEG with quality

const jpegDataUrl = canvas.toDataURL("image/jpeg", 0.85);

The quality argument applies to supported lossy formats. A value of 0 requests the lowest quality and 1 the highest. If the browser does not support the requested type, the export falls back to PNG. Check the returned prefix instead of assuming the request succeeded:

const result = canvas.toDataURL("image/webp", 0.85);
if (result.startsWith("data:image/png")) {
  console.log("WebP was not supported; the browser returned PNG.");
}

See MDN’s toDataURL() reference for format and security behavior.

Draw an image, then export it

const image = new Image();
image.onload = () => {
  const canvas = document.createElement("canvas");
  canvas.width = image.naturalWidth;
  canvas.height = image.naturalHeight;
  canvas.getContext("2d").drawImage(image, 0, 0);

  const dataUrl = canvas.toDataURL("image/png");
  document.querySelector("#result").src = dataUrl;
};
image.src = "photo.png";

If the source is cross-origin and is served without appropriate CORS permission, drawing it can taint the canvas. Calling toDataURL() on that canvas then throws a SecurityError. The restriction protects pixels that the page is not authorized to read.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Which conversion method should you choose?

Situation Recommended method Reason
User selected a local image and no edits are needed FileReader.readAsDataURL() Reads the File or Blob directly and returns a complete data URL.
Image is already drawn on a canvas canvas.toDataURL() Exports the current canvas bitmap, including edits and compositing.
You need cropping, filters, or resizing before encoding Canvas, then toDataURL() Transform first and export the resulting bitmap.
Image is large or must remain independently cacheable Separate image resource, Blob, or object URL Avoid placing a very large encoded string in HTML.

Putting the result into HTML and CSS

Image element

<img id="logo" alt="Company logo">
<script>
  document.querySelector("#logo").src = dataUrl;
</script>

Inline HTML generated from JavaScript

const html = `<img src="${dataUrl}" alt="Uploaded image">`;
document.querySelector("#container").innerHTML = html;

Only insert data you trust into innerHTML. A data URL generated by FileReader for an accepted image is not a substitute for validating file types and handling untrusted application input safely.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • 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

CSS background image

element.style.backgroundImage = `url("${dataUrl}")`;

For a stylesheet that is generated server-side, escape the value according to the context in which it will be inserted. A data URL is still a URL, not an HTML filename.

Performance, size, and caching limits

Data URLs are convenient for small, self-contained assets, but they are not automatically the best choice for every image. toDataURL() materializes the complete encoded image as an in-memory string. MDN warns that large images can hurt performance and may exceed URL-length limits; it says you should generally prefer toBlob() instead for large canvas images.

  • Use inline Base64 for small icons, previews, email fragments, or a document that must contain its image bytes.
  • Use a normal image URL when the browser should cache the file independently or when several pages reuse it.
  • For a large canvas result, use canvas.toBlob() and URL.createObjectURL(blob) rather than building one huge data URL.
  • Release object URLs with URL.revokeObjectURL() when they are no longer needed.
canvas.toBlob((blob) => {
  if (!blob) return;
  const objectUrl = URL.createObjectURL(blob);
  preview.src = objectUrl;
  // Later, when the preview is no longer needed:
  // URL.revokeObjectURL(objectUrl);
}, "image/png");

Base64 itself is text, so embedding it duplicates the image bytes inside the HTML document and can make source, memory, and transport handling heavier. No universal “maximum” image size applies across all browsers and embedding contexts; test the target environment when you must inline a large asset.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common errors and fixes

The image shows a broken icon

  • Cause: You pasted only the Base64 payload.
  • Fix: Add the correct declaration, such as data:image/png;base64,, or use the complete FileReader.result.

reader.result is empty or undefined

  • Cause: The code reads the value immediately after starting the asynchronous operation.
  • Fix: Use the load event, onload, or a promise wrapper and read the result there.

The output is PNG even though JPEG or WebP was requested

  • Cause: The requested canvas format is unsupported.
  • Fix: Inspect the prefix returned by toDataURL(); use PNG when the result starts with data:image/png.

SecurityError from toDataURL()

  • Cause: The canvas contains cross-origin pixels without suitable access-control headers.
  • Fix: Serve the image with the required CORS policy, set image.crossOrigin before assigning its source when appropriate, or use an image hosted on the same origin.

The page becomes slow or the HTML becomes enormous

  • Cause: A large image was encoded into a JavaScript string or document.
  • Fix: Resize before export, use toBlob() and an object URL, or keep the image as a separate resource.

The selected file is not an image

  • Cause: File extensions are not reliable validation.
  • Fix: Use an accept="image/*" hint, check file.type, enforce size limits, and validate again on the server if the file leaves the browser.

Or skip the browser setup

If your actual goal is to obtain a screenshot of a web page rather than encode a user-selected image, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns a PNG, JPEG, WebP, or PDF; it is not a replacement for the browser APIs above when you need to convert a local file or canvas bitmap.

cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

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)

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}`);

See the ScreenshotNeo documentation for request options. Before capture, it can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets, with each cleanup step configurable. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing; response headers identify the page verdict and whether the request was billed. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients. Every plan includes the features, and 1,000 screenshots per month are free without a card; paid plans start at $5 for 3,000 screenshots. Sign up for the free plan.

Security and maintenance considerations

  • Do not assume a filename extension proves the content is an image.
  • Apply size limits before reading or exporting files to avoid avoidable memory pressure.
  • Keep sensitive images out of URLs and logs where possible; data URLs can be copied, stored, and exposed wherever the surrounding HTML or CSS is exposed.
  • Use an accessible alt description for meaningful images. Use an empty alt for purely decorative images.
  • When data is submitted to a server, validate and authorize it there as well as in the browser.

Quick decision checklist

  • Need a local file immediately in an <img>? Use readAsDataURL().
  • Need to export a cropped or edited bitmap? Draw it to a canvas and call toDataURL().
  • Need only raw Base64? Remove everything through the first comma after confirming the consumer requires it.
  • Need to inline a large image? Prefer toBlob(), an object URL, or a normal image resource.
  • Canvas export fails with a security error? Check cross-origin image access and CORS headers.

Frequently Asked Questions

Can I put a Base64 string directly in an img src attribute?

Use a complete data URL, including the media type and ;base64, declaration. A bare encoded payload is not a complete image source.

Does FileReader convert the file synchronously?

No. readAsDataURL() is asynchronous; consume reader.result after the read completes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What format does canvas.toDataURL() use by default?

PNG. If an optional requested format is unsupported, the browser returns PNG instead.

Why is a normal image URL sometimes better than Base64?

Separate resources can remain independently cacheable and avoid placing a large encoded string in HTML or JavaScript.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.