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

Use FileReader.readAsDataURL() to turn a browser File or Blob—including a PNG—into a complete Base64 data URL. For HTML text, encode its UTF-8 bytes before Base64 conversion; btoa() alone is safe only for byte-valued characters, not arbitrary Unicode. In Node.js, use Buffer. The right method depends on whether your input is text, a file, or a canvas, and whether you need a full data URL or just the Base64 payload.

Choose the right Base64 conversion

Base64 represents bytes using text characters. It does not encrypt or compress data. First decide what you have and what the receiving code expects:

  • HTML string: encode its UTF-8 bytes. The result is a Base64 string representing the text.
  • PNG File or Blob in a browser: use FileReader.readAsDataURL() for a complete URL beginning with data:image/png;base64,.
  • Image already drawn to a canvas: use canvas.toDataURL('image/png').
  • PNG file in Node.js: read its bytes and call toString('base64').
  • Raw Base64 required: remove the data-URL prefix only if the destination specifically asks for the payload without the prefix.

A data URL contains a declaration and a payload, for example data:image/png;base64,iVBORw0KGgo.... The declaration tells a consumer the media type and encoding. An HTML image can use the complete data URL as its src; an API that expects raw Base64 may instead reject the prefix.

Convert an HTML string to Base64 in a browser

For plain ASCII text, btoa(html) works. HTML commonly contains non-ASCII characters—such as curly quotes, accented letters, or emoji—so a reliable general solution converts text to UTF-8 bytes first. This example handles Unicode in both directions:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function utf8ToBase64(text) {
  const bytes = new TextEncoder().encode(text);
  let binary = '';
  for (const byte of bytes) binary += String.fromCodePoint(byte);
  return btoa(binary);
}

function base64ToUtf8(base64) {
  const binary = atob(base64);
  const bytes = Uint8Array.from(binary, ch => ch.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}

const html = '<h1>Café ☕</h1>';
const encoded = utf8ToBase64(html);
const restored = base64ToUtf8(encoded);
console.log(encoded);
console.log(restored); // <h1>Café ☕</h1>

TextEncoder produces UTF-8 bytes. The loop builds the binary string expected by btoa(), which then encodes those byte values. To decode, atob() returns a binary string; convert its character codes back to bytes and pass them to TextDecoder to recover UTF-8 text. atob() throws InvalidCharacterError when its input is not valid Base64.

If you know the input is ASCII only, the shorter option is:

const encoded = btoa('<p>Hello</p>');
const decoded = atob(encoded);

Do not use that shortcut on a general JavaScript string. JavaScript strings are Unicode, while btoa() accepts a binary string whose characters represent byte values; characters outside that range can cause an error or require a deliberate encoding step.

Convert a PNG File or Blob to a data URL

In a browser, FileReader.readAsDataURL() reads a Blob or File asynchronously and returns a data URL. A file selected from an input is a File, which is also a Blob:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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
function blobToDataUrl(blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = () => reject(reader.error);
    reader.readAsDataURL(blob);
  });
}

const fileInput = document.querySelector('#png-file');
fileInput.addEventListener('change', async () => {
  const file = fileInput.files[0];
  if (!file) return;

  try {
    const dataUrl = await blobToDataUrl(file);
    console.log(dataUrl); // e.g. data:image/png;base64,...
    document.querySelector('#preview').src = dataUrl;
  } catch (error) {
    console.error('Could not read the image:', error);
  }
});

Use matching markup to select a file and display the result:

<input id="png-file" type="file" accept="image/png">
<img id="preview" alt="Selected PNG preview">

The accept attribute guides the file picker; it is not a guarantee that the chosen file is actually a PNG. If the type matters to your application, validate the selected file rather than trusting the picker hint.

Keep the complete data URL or extract the raw payload

Keep the complete value when assigning it to an image’s src or passing it to a consumer that accepts data URLs. If a service explicitly requests only the Base64 payload, remove the media-type declaration:

const rawBase64 = dataUrl.replace(/^data:[^;]+;base64,/, '');

This expression removes a Base64 data-URL prefix. Do not strip the prefix merely because it looks like extra text: consumers that expect a data URL need the declaration, and consumers expecting raw Base64 need only the payload. MDN notes that the prefix must be removed before decoding the payload as Base64.

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

Convert a canvas image to PNG Base64

If the image is already in a canvas, request a PNG data URL directly:

const pngDataUrl = canvas.toDataURL('image/png');
// Starts with data:image/png;base64,

PNG is a required supported format for toDataURL(). This method serializes the canvas image as a complete data URL, not as raw Base64 alone. The operation creates an in-memory string containing the encoded image, so very large canvases may use substantial memory.

A canvas containing cross-origin image content may not be origin-clean. If the content was loaded without appropriate CORS handling, serialization can fail with a security error. This is a browser security restriction, not a Base64 syntax problem; the source needs to be served with suitable CORS permission before it can be drawn and serialized.

Convert HTML and PNG files in Node.js

Node.js has a byte-oriented Buffer API. Read a PNG as bytes, then encode it with toString('base64'). For HTML text, explicitly use UTF-8 when creating the buffer:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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
import { readFile } from 'node:fs/promises';

const pngBytes = await readFile('image.png');
const pngBase64 = pngBytes.toString('base64');
const html = '<h1>Café ☕</h1>';
const htmlBase64 = Buffer.from(html, 'utf8').toString('base64');

const decodedPngBytes = Buffer.from(pngBase64, 'base64');
const decodedHtml = Buffer.from(htmlBase64, 'base64').toString('utf8');

console.log(pngBase64);
console.log(htmlBase64);
console.log(decodedHtml);

The PNG result is a Base64 representation of the image bytes, not a data URL. To construct a URL for an image consumer, add the appropriate prefix yourself:

const pngDataUrl = `data:image/png;base64,${pngBase64}`;

Conversely, if a Node.js program receives a PNG data URL but needs its payload, split off the declaration before decoding:

const dataUrl = 'data:image/png;base64,...';
const rawBase64 = dataUrl.replace(/^data:[^;]+;base64,/, '');
const pngBytes = Buffer.from(rawBase64, 'base64');

Node.js documents Buffer.from(value, 'base64') and buffer.toString('base64') as the preferred methods for converting Base64 strings and binary data in Node.js API code. Use these rather than the browser-compatibility buffer.atob() or buffer.btoa() functions for new Node.js code.

What to do with the result

Embedding an image in HTML

For an image already represented by a complete data URL, use that URL directly:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<img src="data:image/png;base64,..." alt="Example">

For a programmatically generated value, assign the string to the element’s src. If your value is only raw Base64, prepend the correct media type and encoding declaration first. The declaration must match the actual content; labeling other bytes as PNG does not convert them into a PNG.

Sending HTML or an image to another system

Check the receiving system’s contract before choosing the representation. It may want a complete data URL, a raw Base64 payload, or the original bytes as a file or binary request body. These forms are not interchangeable without adjusting the prefix or decoding. Base64 is an encoding, not protection: do not treat it as a way to hide sensitive HTML or image contents.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance and memory considerations

Base64 conversion produces a textual representation of the input bytes. Browser data-URL APIs also place that representation in memory as a string; for large images, retaining the original file, encoded string, preview URL, and copies passed between components can increase memory use. Avoid creating several unnecessary copies. If the next step can consume a file or binary data directly, that may avoid building a large Base64 string at all.

Canvas toDataURL() specifically serializes the whole image into an in-memory string. Choose it when a data URL is what the next step needs, not simply because the image happens to be on a canvas. No general speed or size benchmark follows from the API documentation; the result depends on the input and runtime.

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

Troubleshoot common Base64 problems

  • btoa() fails on accented characters or emoji: the input is Unicode text, not a binary string of byte values. Encode with TextEncoder first, as shown above.
  • atob() throws InvalidCharacterError: check that the input is valid Base64 and remove a data-URL prefix before decoding the payload. Do not pass data:image/png;base64, as if it were Base64 data.
  • The image preview does not appear: determine whether the value is a complete data URL or raw Base64. An <img src> needs a usable URL; raw payload alone is missing the media declaration.
  • Canvas serialization raises a security error: cross-origin content may have made the canvas non-origin-clean. Load content with appropriate CORS handling before drawing it, then serialize.
  • The output is unexpectedly large or memory-intensive: data URLs are strings containing an encoded copy of the data. Avoid unnecessary conversions and copies, particularly for large images.
  • A selected file is not actually PNG: the file input’s accept value is a picker hint, not format validation. Validate file type and content as required by the application.
  • Decoded HTML has garbled non-ASCII characters: ensure the text was encoded and decoded as UTF-8 bytes. On Node.js, use Buffer.from(text, 'utf8') and decode with toString('utf8').

Or skip the browser setup

If what you need first is a website screenshot, ScreenshotNeo can capture the page as an image; you can then Base64-encode the downloaded image with the browser or Node.js methods above. The API returns an image or PDF, not a Base64 string. Its one-request API is documented at ScreenshotNeo docs:

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

ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before capture; each cleanup step can be turned off. Bot checks or 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 gives AI agents tools for screenshots, page information, and PDF capture. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, with no card.

Frequently asked questions

Does Base64 encrypt an HTML file or PNG?

No. Base64 is an encoding for representing bytes as text, not encryption. Anyone with the encoded value can decode it.

Does converting HTML text to Base64 make it safe to insert into a page?

No. Encoding does not sanitize HTML or make untrusted markup safe to render. Apply the security controls appropriate to how the decoded content will be used.

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

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.