How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Convert an Image to a Base64 String in JavaScript
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • 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.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Laravel Eloquent ORM — a model class mapping to a database table with query methods
Laravel Eloquent ORM: The Complete Guide to Querying Your Database
June 16, 2026
Set vi as the default editor in Ubuntu — a terminal opening the vim editor
How to Set vi (Vim) as the Default Editor in Ubuntu
June 8, 2026
rsync says ALL DONE but files are missing — a terminal showing ALL DONE next to an empty folder
rsync Says “ALL DONE” but Files Are Missing: How to Verify
June 8, 2026
Migrate a website to a new server with rsync — files copying from an old server to a new one over SSH
How to Migrate a Website to a New Server With rsync
June 8, 2026
Bun runtime — faster JS toolkit replacing npm in Laravel projects
How to Install Bun Runtime on Ubuntu (And Use It in a Laravel Project)
May 24, 2026

You Might Also Like

Rename menu items on the WooCommerce My Account page
Web Development

How to Rename Menu Items on the WooCommerce My Account Page

4 Min Read
Laravel migration adding two new columns to an existing transactions table
Web Development

How to Add New Columns to an Existing Table in Laravel Migration

5 Min Read
Store a PHP array in a MySQL database with JSON
Web Development

How to Store a PHP Array in a MySQL Database

5 Min Read
Send a simple email in Laravel using Mail::raw and SMTP
Web Development

How to Send a Simple Email in Laravel (Fast SMTP + Mail::raw)

4 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • 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?