How7oHow7o
  • Home
  • Tools
    • All Tools
    • Image Tools
    • Text & String Tools
    • Video Tools
    • Developer Tools
    • PDF Tools
    • Calculators & More
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Convert an Image to a Base64 String in JavaScript
Share
Notification Show More
Font ResizerAa
How7oHow7o
Font ResizerAa
  • Tools
  • Prank Screens
  • Learn
  • Blog
Search
  • Home
  • Tools
    • All Tools
    • Image Tools
    • Text & String Tools
    • Video Tools
    • Developer Tools
    • PDF Tools
    • Calculators & More
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Convert an Image to a Base64 String in JavaScript
Web Development

How to Convert an Image to a Base64 String in JavaScript

how7o
By how7o
Last updated: May 22, 2026
5 Min Read
Convert an image to a base64 data URL in JavaScript
SHARE

To convert an image to a base64 string in JavaScript, fetch the image as a Blob and pass it to FileReader.readAsDataURL(). The result is a full data:image/...;base64,... URL ready to use anywhere an image URL works. For images that are already loaded in the page (or that you’ve drawn yourself), canvas.toDataURL() is the alternative.

Contents
  • TL;DR — fetch + FileReader
  • Files picked by the user (<input type="file">)
  • Alternative — canvas toDataURL()
  • When to use which
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-05-17 on Chrome 124, Firefox 125, Safari 17. Originally published 2022-09-21, rewritten and updated 2026-05-17.

TL;DR — fetch + FileReader

async function imageUrlToBase64(url) {
  const blob = await fetch(url).then(r => r.blob());
  return await new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.onerror   = reject;
    reader.readAsDataURL(blob);
  });
}

const dataUrl = await imageUrlToBase64('/path/to/image.png');
// "data:image/png;base64,iVBORw0KGgoAAAA..."

FileReader.readAsDataURL() already produces the complete data URL — you do not need to prepend data:image/png;base64, yourself, and you don’t need to call btoa(). The MIME type comes from the Blob’s type field, which the browser sets from the response’s Content-Type.

JavaScript image to base64 — fetch + FileReader, canvas + toDataURL, file input flow

Files picked by the user (<input type="file">)

When the image comes from a file input there’s no network step — you already have a File:

const input = document.querySelector('input[type=file]');
input.addEventListener('change', () => {
  const file = input.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onloadend = () => {
    console.log(reader.result); // data:image/...;base64,...
  };
  reader.readAsDataURL(file);
});

Alternative — canvas toDataURL()

If the image is already in the DOM, or you want to re-encode to a different format (e.g. JPEG with quality), draw it to a canvas and call toDataURL():

function imageElementToBase64(img, mime = 'image/png', quality) {
  const canvas = document.createElement('canvas');
  canvas.width  = img.naturalWidth;
  canvas.height = img.naturalHeight;
  canvas.getContext('2d').drawImage(img, 0, 0);
  return canvas.toDataURL(mime, quality);
}

const img = document.querySelector('img');
const dataUrl = imageElementToBase64(img, 'image/jpeg', 0.85);

If the image is from a different origin, set img.crossOrigin = 'anonymous' before setting img.src, and make sure the remote server returns Access-Control-Allow-Origin. Otherwise the canvas becomes tainted and toDataURL() throws a SecurityError — see MDN’s CORS-enabled image guide.

When to use which

  • Image at a URL → base64: fetch + FileReader. Preserves the original encoding (PNG stays PNG).
  • User-selected file → base64: FileReader directly on the File. No network.
  • Already-rendered image → base64, or re-encode format: canvas + toDataURL(). Watch out for CORS taint.
  • Already-rendered image → base64, you don’t want to re-encode: Use fetch on the image’s URL instead. Canvas always re-encodes, which loses original compression.

Frequently asked questions

Is there a built-in JS function like PHP’s base64_encode for images?

Not directly. btoa() only encodes strings (and only Latin-1), so you can’t hand it an image and get a data URL back. The two browser-native paths are FileReader.readAsDataURL() on a Blob, or a canvas with canvas.toDataURL(). Both produce a complete data:image/...;base64,... string, ready to drop into <img src>.

Why does canvas.toDataURL() sometimes throw a security error?

If you draw an image from a different origin onto a canvas without proper CORS headers from that server, the canvas is marked tainted and any read attempt (toDataURL(), getImageData()) throws a SecurityError. The fix is on the image’s host: it must serve Access-Control-Allow-Origin for the request, and you must set img.crossOrigin = 'anonymous' before assigning src.

Should I use this for files the user picks with <input type="file">?

Yes — but skip the network step. The change event gives you a File object (a kind of Blob) directly, so pass it to FileReader.readAsDataURL() right away. No fetch or XMLHttpRequest needed.

How big is the base64 string vs the original image?

Base64 inflates binary data by roughly 33% (3 bytes encode to 4 characters), plus the data:image/png;base64, prefix. A 100 KB PNG becomes about a 134 KB data URL. Inline base64 makes sense for tiny icons or one-off uploads — for many or large images, prefer keeping them as files.

Related guides

  • How to Check if a Checkbox Is Checked with jQuery
  • How to Check if a JavaScript String Is a Valid URL

References

FileReader.readAsDataURL(): developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL. HTMLCanvasElement.toDataURL(): developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL. Canvas taint: developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image.

TAGGED:base64imageJavaScript

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Nginx subdirectory configuration with alias and PHP-FPM How to Configure Nginx for a Subdirectory
Next Article Create a folder in PHP if it does not already exist How to Create a Folder If It Does Not Exist in PHP
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

You Might Also Like

WordPress $wpdb->insert_id — read after $wpdb->insert or $wpdb->query INSERT
Web Development

How to Retrieve the Last Inserted Row ID in WordPress

7 Min Read
Get the last item from a PHP array
Web Development

How to Get the Last Item from an Array in PHP

5 Min Read
Run JS code on URL hash change with the hashchange event
Web Development

How to Run Code on URL Hash Change in JavaScript

4 Min Read
Select the last child element with jQuery
Web Development

How to Select the Last Child Element in jQuery

4 Min Read
How7oHow7o

Free browser-based tools, prank screens, and step-by-step tech tutorials. No signup, nothing uploaded.

  • Private by design — your files never leave your device
  • Instant — no signup, no install, no waiting
  • Always free — no trials, no watermarks, no paywalls

Tools

  • PDF Editor
  • Image Upscaler
  • JPEG Compressor
  • Password Generator
  • QR Code Generator
  • Video Trimmer
  • See all tools →

Pranks

  • Cracked Screen Prank
  • Fake Blue Screen (BSOD)
  • Fake Disk Format
  • Fake Low Battery
  • Fake Nintendo Switch Update Screen
  • Fake PlayStation Update Screen
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?