Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
Base64

How to Convert an HTML Image to PNG Base64

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

To convert an already-loaded HTML <img> to PNG Base64 in the browser, draw it onto a canvas sized to the image’s intrinsic dimensions, then call canvas.toDataURL("image/png"). That returns a complete data URL beginning data:image/png;base64,; remove that prefix only if the receiving system specifically wants the Base64 payload alone. For a remote image, the image server must permit canvas access through CORS or the browser will block the export.

Convert an image element to a PNG data URL

This function accepts a loaded HTMLImageElement and returns a PNG data URL. It uses naturalWidth and naturalHeight, which describe the image’s intrinsic dimensions rather than its displayed CSS size.

function imageToPngDataUrl(img) {
  if (!(img instanceof HTMLImageElement)) {
    throw new TypeError("Expected an HTMLImageElement");
  }
  if (!img.complete || img.naturalWidth === 0 || img.naturalHeight === 0) {
    throw new Error("Image is not loaded or has no usable dimensions");
  }

  const canvas = document.createElement("canvas");
  canvas.width = img.naturalWidth;
  canvas.height = img.naturalHeight;

  const context = canvas.getContext("2d");
  if (!context) throw new Error("Canvas 2D context is unavailable");

  context.drawImage(img, 0, 0);
  return canvas.toDataURL("image/png");
}

For an image already in the document, call the function after it has loaded:

const img = document.querySelector("#source-image");

if (!img) {
  throw new Error("Image element not found");
}

if (img.complete && img.naturalWidth > 0) {
  const pngDataUrl = imageToPngDataUrl(img);
  console.log(pngDataUrl);
} else {
  img.addEventListener("load", () => {
    const pngDataUrl = imageToPngDataUrl(img);
    console.log(pngDataUrl);
  }, { once: true });

  img.addEventListener("error", () => {
    console.error("The image could not be loaded");
  }, { once: true });
}

The check for complete handles the case where the image finished loading before your code attached a listener. The nonzero intrinsic-dimension check distinguishes a usable image from an element whose request has not produced a decoded image. If you create an image in JavaScript, install listeners before assigning its source.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
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

Load a URL into a new image element

function loadImage(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();

    img.onload = () => resolve(img);
    img.onerror = () => reject(new Error(`Could not load image: ${url}`));
    img.src = url;
  });
}

const img = await loadImage("/images/example.jpg");
const pngDataUrl = imageToPngDataUrl(img);

This example works for a same-origin image, subject to successful loading. For a cross-origin URL that you need to export, set crossOrigin before src and ensure the server grants access; see the CORS section below.

Return raw Base64 instead of the full data URL

toDataURL("image/png") returns a string with a media-type declaration and an encoded payload. A typical result starts with data:image/png;base64,. If your API or storage format expects only the Base64 characters, strip everything through the first comma:

const dataUrl = imageToPngDataUrl(img);
const comma = dataUrl.indexOf(",");

if (comma === -1) {
  throw new Error("Unexpected data URL format");
}

const base64 = dataUrl.slice(comma + 1);

Do not strip the prefix by default. Many consumers expect the complete data URL, while others require raw Base64 or binary bytes. Check the receiving API’s contract before changing the representation. If it expects a data URL, pass dataUrl; if it explicitly asks for Base64 content, pass base64.

Choose the right canvas dimensions

The canvas dimensions determine the pixel dimensions of the exported PNG. Setting them to naturalWidth and naturalHeight preserves the image’s intrinsic pixel size. An image displayed at 300 CSS pixels wide may have more intrinsic pixels than that, so using img.width or a CSS measurement can unintentionally reduce the output resolution.

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

If you deliberately want a resized result, set the canvas to the output dimensions and provide the destination rectangle to drawImage:

const outputWidth = 600;
const outputHeight = Math.round(
  img.naturalHeight * outputWidth / img.naturalWidth
);

const canvas = document.createElement("canvas");
canvas.width = outputWidth;
canvas.height = outputHeight;

const context = canvas.getContext("2d");
if (!context) throw new Error("Canvas 2D context is unavailable");

context.drawImage(img, 0, 0, outputWidth, outputHeight);
const resizedPngDataUrl = canvas.toDataURL("image/png");

Canvas has finite size limits that vary by browser and device. An extremely large canvas can fail or serialize as the empty data URL data:,. Check both the dimensions and the returned value when processing unusually large images.

Handle remote images and CORS

A cross-origin image can appear normally in an <img> and still be unavailable for pixel readback. If the browser draws a cross-origin image without the required permission, it taints the canvas. Calling toDataURL(), toBlob(), or getImageData() on that canvas then raises a SecurityError.

For a CORS-enabled image, request it in CORS mode before starting the request:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function loadCorsImage(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = "anonymous";
    img.onload = () => resolve(img);
    img.onerror = () => reject(new Error("Image load or CORS request failed"));
    img.src = url;
  });
}

const img = await loadCorsImage("https://example.com/image.png");
const pngDataUrl = imageToPngDataUrl(img);

The remote server must respond with an appropriate Access-Control-Allow-Origin header permitting the requesting page’s origin. Setting crossOrigin requests CORS; it does not grant permission or override the server’s policy. If you control the image server, configure its CORS response for the origins that should be allowed. Otherwise, use a same-origin image or ask the host to permit access. A client-side proxy is not a browser API workaround for a host’s access policy.

Use a Blob when a Base64 string is unnecessary

Base64 is useful when a consumer explicitly requires text, such as a JSON field that accepts a data URL. It is often an unnecessary intermediate when the next operation can accept binary data. toDataURL() materializes the entire encoded result as a JavaScript string, which can consume substantial memory for large images.

MDN recommends generally preferring toBlob(), together with URL.createObjectURL(), where the workflow allows it. For example, a canvas can produce a PNG Blob without first building a Base64 data URL:

function canvasToPngBlob(canvas) {
  return new Promise((resolve, reject) => {
    canvas.toBlob(blob => {
      if (blob) resolve(blob);
      else reject(new Error("PNG encoding failed"));
    }, "image/png");
  });
}

const blob = await canvasToPngBlob(canvas);
// Pass `blob` to an upload API or create an object URL when needed.

This does not produce Base64. If the final consumer specifically requires Base64, encoding the Blob as a data URL still creates a string and has memory costs. Prefer the binary path when the receiving API supports it.

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

Read a File or Blob without converting its image format

If your input is already a File or Blob and it is already in the format you need, FileReader.readAsDataURL() reads its existing bytes and returns a data URL:

function blobToDataUrl(blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = () => reject(reader.error || new Error("File read failed"));
    reader.readAsDataURL(blob);
  });
}

const dataUrl = await blobToDataUrl(file);
const base64 = dataUrl.slice(dataUrl.indexOf(",") + 1);

This encodes the file’s existing content; it does not turn a JPEG or WebP into PNG. To transcode an image to PNG, load and draw it through canvas, then export with toDataURL("image/png") or toBlob(..., "image/png").

Troubleshoot common failures

The image appears, but export throws SecurityError

The canvas is tainted, usually because the image came from another origin without a successful CORS grant. Set img.crossOrigin = "anonymous" before assigning the source and verify that the image server sends an appropriate Access-Control-Allow-Origin response. If the server does not grant access, use an image on your own origin or obtain permission from its operator.

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

The output is empty, tiny, or data:,

Check that the image loaded, that naturalWidth and naturalHeight are nonzero, and that the canvas dimensions are valid. An empty data:, is not a successful PNG data URL; it can indicate a zero-sized or oversized canvas. Reduce the output dimensions if appropriate and verify the actual values before drawing.

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

The canvas context is null

getContext("2d") can return null. Check it before calling drawImage, as in the examples. If the context is unavailable, the conversion cannot proceed through that canvas.

The image is blank or drawing has no effect

Wait for the image’s load event before drawing. When the source is assigned in script, attach both load and error handlers first. Also check for a failed request, a zero intrinsic width or height, and whether the selected image element is the one you intended.

The result is PNG, but the source was JPEG or WebP

That is expected when exporting the canvas with "image/png": the browser serializes the rendered pixels as PNG. By contrast, reading the original File with FileReader preserves the original file bytes and format.

The Base64 value is rejected by the receiving API

Confirm whether it wants the complete data URL, only the substring after the comma, or binary bytes. Also confirm that it accepts PNG and that the value is sent in the expected field or content type. Do not assume that a data URL and raw Base64 are interchangeable.

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

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server, not a direct replacement for converting an arbitrary existing <img> element. If your real input is a public webpage and you want a screenshot file, one request can capture the page; that returned image can then be converted to Base64 by your application if needed. See the ScreenshotNeo site and the 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

ScreenshotNeo accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each of those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients. The free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots.

Sign up free for ScreenshotNeo to get 1,000 screenshots a month with no card.

Frequently Asked Questions

Does Base64 conversion encrypt or protect an image?

No. Base64 is an encoding of bytes, not encryption or access control. Treat the resulting string as the image content itself.

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

Will this preserve transparency?

PNG supports transparency, and canvas PNG export can retain transparent pixels in the rendered image. The exported result reflects what was drawn onto the canvas.

Can I use this code in Node.js without a browser?

The examples use browser APIs such as `HTMLImageElement`, `document`, and canvas. A Node.js environment needs a separate image/canvas implementation; these browser snippets are not directly runnable there.

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.