HTML

<img id="imageid" src="https://www.google.de/images/srpr/logo11w.png">

JavaScript

function getBase64Image(img) {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);
  var dataURL = canvas.toDataURL("image/png");
  return dataURL.replace(/^data:image\/?[A-z]*;base64,/);
}

var base64 = getBase64Image(document.getElementById("imageid"));

Special thanks to @Md. Hasan Mahmud for providing an improved regex that works with any image mime type in my comments!

This method requires the canvas element, which is perfectly supported.

  • The MDN reference of HTMLCanvasElement.toDataURL().
  • And the official W3C documentation.
Answer from ˈvɔlə on Stack Overflow
🌐
Tick
pqina.nl › blog › convert-an-image-to-a-base64-string-with-javascript
Convert An Image To A DataURL or Base64 String Using JavaScript - Pqina
We’ll be converting images to DataURLs, we can use the function below to convert a DataURL to a Base64 string. const getBase64StringFromDataURL = (dataURL) => dataURL.replace('data:', '').replace(/^.+,/, ''); Let’s get started. When the image is a File object or Blob we can use the FileReader API please see this article on converting a file to base64 string or dataURL.
Discussions

How can I convert an image into Base64 string using JavaScript? - Stack Overflow
I need to convert my image to a Base64 string so that I can send my image to a server. Is there any JavaScript file for this? Else, how can I convert it? More on stackoverflow.com
🌐 stackoverflow.com
How to convert image URI to base64. | OutSystems
I want to store the base64 data of Image URI in a local variable. Can anyone come up with some idea how I can do it · There's nothing out-of-the-box that supports this. If you google a bit you'll find ways to do that with JavaScript, e.g. here More on outsystems.com
🌐 outsystems.com
April 15, 2023
Is there a way to convert the s3 image URL to base64 in nodejs
If the S3 object is publicly available, node-fetch can get the buffer, which you can then convert to base64, had to do this myself today. More on reddit.com
🌐 r/node
9
3
August 23, 2022
Is there a way to convert the s3 image URL to base64.?

You don’t want to convert the URL to base64, how would that help? You want to convert the image content to base64.

More on reddit.com
🌐 r/learnjavascript
3
1
August 23, 2022
🌐
Base64.Guru
base64.guru › home › base64 converter › base64 encode
Image to Base64 | Base64 Encode | Base64 Converter | Base64
If you do not know what output format you need, check the following examples to see how will look the result of the same Base64-encoded image formatted in each of the available formats (as an example image I use a one-pixel red dot GIF file):• Plain text: R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs=• Data URI: data:image/gif;base64,R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs=• CSS Background Image: .base64 { background-image: url("data:image/gif;base64,R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs=") }• HTML Favicon:
🌐
npm
npmjs.com › package › image-to-base64
image-to-base64 - npm
Generate a base64 code from an image through a URL or a path.
      » npm install image-to-base64
    
Published: Apr 09, 2021
Version: 2.2.0
🌐
Formspree
formspree.io › blog › image-to-base64
How to Convert an Image URL to Base64 | Formspree
August 28, 2024 - Fetching the Image: The Fetch API enables you to make a request to the image URL, retrieving the image data as a response object. Converting to ArrayBuffer: The response object typically contains the image data in a binary format. You can use the arrayBuffer() method to convert this binary data into an ArrayBuffer, a more efficient representation for manipulation. Base64 Encoding with btoa: Once you have the image data as an ArrayBuffer, you can leverage the built-in btoa function in JavaScript.
🌐
Bobby Hadz
bobbyhadz.com › blog › convert-image-to-base64-using-node
Convert an Image or an Image URL to base64 in Node.js | bobbyhadz
The imageUrlToBase64() function takes the complete URL that points to the image as a parameter and converts the image URL to a base64 string.
🌐
Medium
medium.com › @j622amilah › javascript-basics-45-154fcf627ab5
JavaScript Basics 45. Image url fetch, base64 encoding for… | by Practicing DatScy | Medium
May 19, 2026 - In this post, an image is fetched from a URL as an ArrayBuffer. The ArrayBuffer is then encoded to a format that is standard for database storage, a base64 string. The base64 string is then used to display the original image to test that the ...
🌐
TutorialsPoint
tutorialspoint.com › converting-images-to-a-base64-data-url-using-javascript
Convert Image to Data URI with JavaScript
August 26, 2022 - Use Canvas API with toDataURL() for converting image URLs to Data URI, and FileReader API for local files. Both methods produce Base64-encoded strings that can be used directly in HTML or stored for later use.
Find elsewhere
🌐
Staxmanade
staxmanade.com › 2017 › 02 › how-to-download-and-convert-an-image-to-base64-data-url
How to Download and Convert an Image to Base64 Data Url - Developing on Staxmanade
February 26, 2017 - async function getBase64ImageFromUrl(imageUrl) { var res = await fetch(imageUrl); var blob = await res.blob(); return new Promise((resolve, reject) => { var reader = new FileReader(); reader.addEventListener("load", function () { resolve(reader.result); }, false); reader.onerror = () => { return ...
🌐
GitConnected
levelup.gitconnected.com › how-to-convert-image-to-base64-by-javascript-d110556de37f
How to Convert Image to Base64 with Javascript | by bitbug | Level Up Coding
January 16, 2023 - The following function converts ... call this function // we can wrap this function to Promise-based // function convertImageToBase64Async(imagUrl) { // return new Promise(resovle => convertImageToBase64(imgUrl, resolve)) ...
🌐
DEV Community
dev.to › dcodeyt › how-to-convert-images-to-base64-data-urls-in-javascript-2n3i
How to Convert Images to Base64 Data URLs in JavaScript - DEV Community
August 31, 2022 - const fileInput = document.getElementById("fileInput"); fileInput.addEventListener("change", e => { const file = fileInput.files[0]; const reader = new FileReader(); reader.addEventListener("load", () => { // Base64 Data URL 👇 console.log(reader.result); }); reader.readAsDataURL(file); }); Done! Feel free to use this Data URL in your <img> tags. Just don't make the images too large 😎 · If you're learning web development, you can find a complete course on the JavaScript DOM at the link below 👇 https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1
🌐
Stack Abuse
stackabuse.com › bytes › converting-images-and-image-urls-to-base64-in-node-js
Converting Images and Image URLs to Base64 in Node.js
August 19, 2023 - In Node.js, converting an image URL to Base64 can be achieved using the request module along with the built-in Buffer class.
🌐
W3docs
w3docs.com › javascript
How to Convert the Image into a Base64 String Using JavaScript | W3Docs
There are several approaches in JavaScript that can help you with converting the image into a Base64 string. Firstly, create a canvas, then load the image into it and use toDataURL() to get the Base64 representation. In fact, it is a data URL, ...
🌐
YouTube
youtube.com › watch
How to Convert Images Into Base 64 Data URLs with JavaScript - YouTube
In today's tutorial I'll show you how to convert an image to data URL in JavaScript. This is very easy to do by using the FileReader object.For your referenc...
Published: August 16, 2022
🌐
Plain English
plainenglish.io › home › blog › javascript › a comprehensive guide to converting images to base64 with javascript
A Comprehensive Guide to Converting Images to Base64 with JavaScript
May 5, 2023 - To convert an image to base64 from an image URL in JavaScript, you can use the fetch API to get the image data, and then use the FileReader API to read the image data as a base64 string.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-convert-image-into-base64-string-using-javascript
Convert image into base64 string using JavaScript - GeeksforGeeks
February 25, 2026 - <!DOCTYPE html> <html> <head> <title> How to convert image into base64 string using JavaScript ? </title> </head> <body> <input type="file" name="" id="fileId" onchange="imageUploaded()"> <br><br> <button onclick="displayString()"> Display String </button> <script> let base64String = ""; function imageUploaded() { let file = document.querySelector( 'input[type=file]')['files'][0]; let reader = new FileReader(); console.log("next"); reader.onload = function () { base64String = reader.result.replace("data:", "") .replace(/^.+,/, ""); imageBase64Stringsep = base64String; // alert(imageBase64Stringsep); console.log(base64String); } reader.readAsDataURL(file); } function displayString() { console.log("Base64String about to be printed"); alert(base64String); } </script> </body> </html>
🌐
JavaScript in Plain English
javascript.plainenglish.io › how-to-get-image-data-as-a-base64-url-in-javascript-223a0f2dc514
How to Get Image Data as a Base64 URL in JavaScript? | by John Au-Yeung | JavaScript in Plain English
July 7, 2021 - Then we can call the canvas’s toDataURL method to convert it into a base64 string. ... const getBase64Image = (url) => { const img = new Image(); img.setAttribute('crossOrigin', 'anonymous'); img.onload = () => { const canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; const ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); const dataURL = canvas.toDataURL("image/png"); console.log(dataURL) } img.src = url }getBase64Image('https://uploads.sitepoint.com/wp-content/uploads/2015/12/1450377118cors3.png')
Top answer
1 of 16
1216

There are multiple approaches you can choose from:

1. Approach: FileReader

Load the image as blob via XMLHttpRequest and use the FileReader API (readAsDataURL()) to convert it to a dataURL:

function toDataURL(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
      callback(reader.result);
    }
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
}

toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
  console.log('RESULT:', dataUrl)
})

This code example could also be implemented using the WHATWG fetch API:

const toDataURL = url => fetch(url)
  .then(response => response.blob())
  .then(blob => new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result)
    reader.onerror = reject
    reader.readAsDataURL(blob)
  }))


toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0')
  .then(dataUrl => {
    console.log('RESULT:', dataUrl)
  })

These approaches:

  • have better compression
  • work for other file types as well

Browser Support:

  • http://caniuse.com/#feat=filereader
  • http://caniuse.com/#feat=fetch

Tip: To convert local files, you can use live-server. Once started on the folder that contains the picture to transform, open the url in browser and using developer console you can convert the image to base 64.


2. Approach: Canvas (for legacy browsers)

Load the image into an Image-Object, paint it to a nontainted canvas and convert the canvas back to a dataURL.

function toDataURL(src, callback, outputFormat) {
  var img = new Image();
  img.crossOrigin = 'Anonymous';
  img.onload = function() {
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var dataURL;
    canvas.height = this.naturalHeight;
    canvas.width = this.naturalWidth;
    ctx.drawImage(this, 0, 0);
    dataURL = canvas.toDataURL(outputFormat);
    callback(dataURL);
  };
  img.src = src;
  if (img.complete || img.complete === undefined) {
    img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    img.src = src;
  }
}

toDataURL(
  'https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0',
  function(dataUrl) {
    console.log('RESULT:', dataUrl)
  }
)

In detail

Supported input formats:

image/png, image/jpeg, image/jpg, image/gif, image/bmp, image/tiff, image/x-icon, image/svg+xml, image/webp, image/xxx

Supported output formats:

image/png, image/jpeg, image/webp(chrome)

Browser Support:

  • http://caniuse.com/#feat=canvas
  • Internet Explorer 10 (Internet Explorer 10 just works with same origin images)


3. Approach: Images from the local file system

If you want to convert images from the users file system you need to take a different approach. Use the FileReader API:

function encodeImageFileAsURL(element) {
  var file = element.files[0];
  var reader = new FileReader();
  reader.onloadend = function() {
    console.log('RESULT', reader.result)
  }
  reader.readAsDataURL(file);
}
<input type="file" onchange="encodeImageFileAsURL(this)" />

2 of 16
233

You can use the HTML5 <canvas> for it:

Create a canvas, load your image into it and then use toDataURL() to get the Base64 representation (actually, it's a data: URL, but it contains the Base64-encoded image).

🌐
OutSystems
outsystems.com › forums › discussion › 87490 › how-to-convert-image-uri-to-base64
How to convert image URI to base64. | OutSystems
April 15, 2023 - I want to store the base64 data of Image URI in a local variable. Can anyone come up with some idea how I can do it · There's nothing out-of-the-box that supports this. If you google a bit you'll find ways to do that with JavaScript, e.g. here