You can just create an Image object and put the base64 as its src, including the data:image... part like this:

var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

It's what they call "Data URIs" and here's the compatibility table for inner peace.

Answer from Joseph on Stack Overflow
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).

Discussions

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
[SOLVED] How to upload Base64 images with the JavaScript SDK - Integrations & API - Ghost Forum
Hi there, I have the following Node function that uses the JavaScript SDK in order to upload images found in an HTML file: // Utility function to find and upload any images in an HTML string function processImagesInHTM… More on forum.ghost.org
🌐 forum.ghost.org
0
November 13, 2023
How to convert image data from $http response to base64 image
How to convert image data from $http response to base64 image More on github.com
🌐 github.com
1
1
January 13, 2025
How to convert local image into base64 encoding
I am using API to create test execution with evidence attaching as well. So, used prerequiste tab to generate base64 encoded which used in data in evidence tag. I am facing issues in prerequiste script. unable to upload attachment and even evidence attached getting error ‘The requested content ... More on community.postman.com
🌐 community.postman.com
5
0
December 6, 2023
🌐
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
If our image is an <img> element we can fetch the image src and convert that to a Base64 string. Alternatively we can draw the image to a canvas and then convert the canvas to an image element, this would be useful if we’re looking for a specific ...
🌐
Base64 Image Encoder
base64-image.de
Convert Images to Base64 Online — Free Encoder & Optimizer | base64-image.de
Base64 encoding ensures complete ... on external resources. Drag and drop your images onto this page (or click to select files), and they are uploaded securely via HTTPS to our server....
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-convert-base64-to-file-in-javascript
How to Convert Base64 to File in JavaScript? - GeeksforGeeks
August 30, 2024 - In web development, Base64 encoding ... such as images or files, with a string of ASCII characters, sometimes you may be required to change this Base64 string back into a file for instance for file uploads, downloads, or processing in the browser, this article aims to discuss different ways of converting Base64 strings to file objects in JavaScript...
🌐
Jam
jam.dev › utilities › image-to-base64
Image to Base64 Converter | Free, Open Source & Ad-free
Jam's free tool to convert images to Data URI comes in handy when you need to reduce HTTP requests. Convert images to base64 so you can embed them directly into HTML, CSS, or JavaScript.
Find elsewhere
🌐
Medium
medium.com › @divinehycenth8 › convert-a-base64-data-into-an-image-in-node-js-d82136576e35
Convert a Base64 data into an Image in Node.js | by Divine Hycenth | Medium
November 15, 2020 - The Buffer object provides several methods to perform different encoding and decoding conversions. This includes to and from UTF-8, UCS2, Base64, ASCII, UTF-16, and even the HEX encoding scheme. Let us first of all convert our image into base64 and then to Buffer
🌐
Mendix
community.mendix.com › link › spaces › java-actions › questions › 103928
Image to base64 using JavaScript in native app
November 17, 2020 - Hi Erwin, I'm searching for image to base64 in javaScript. not the string to base64 encode and decode. ... The JavaScript engine in the Native React client is JavaScript Core https://reactnative.dev/docs/javascript-environment (a Fun fact, when debugging the environment is the v8 of your browser, this explains way it might work while debugging but on on the device) This JsCore does not support the same function as v8 on the web. So there is no easy way to convert a file to base 64 in both directions.
🌐
GitHub
gist.github.com › barbietunnie › 5fa07012925ee0fe53a0
Decode base64 image in javascript · GitHub
function decodeBase64Image(dataString) { var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/), response = {}; if (matches.length !== 3) { return new Error('Invalid input string'); } response.type = matches[1]; let buf = ...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-convert-image-into-base64-string-using-javascript
Convert image into base64 string using JavaScript - GeeksforGeeks
February 25, 2026 - It converts binary image data into a text-based Base64 encoded string. The Base64 string can be easily stored, transmitted, or embedded directly in HTML or CSS. This can be done using the FileReader object in browsers or the Buffer class in Node.js. Here we will create a gfg.js file which will include JavaScript code and one gfg.html file.
🌐
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
🌐
Ghost Forum
forum.ghost.org › integrations & api
[SOLVED] How to upload Base64 images with the JavaScript SDK - Integrations & API - Ghost Forum
November 13, 2023 - Hi there, I have the following Node function that uses the JavaScript SDK in order to upload images found in an HTML file: // Utility function to find and upload any images in an HTML string function processImagesInHTM…
🌐
Base64.Guru
base64.guru › converter › decode › image
Base64 to Image | Base64 Decode | Base64 Converter | Base64
The following article also didn't ... of the receipt printing; you want the image bits instead! However, the very page you linked to might have all the information you need! Scrolling up, you'll see some references to a JavaScript library they have developed, StarWebPrintB...
🌐
GitHub
github.com › pocketbase › pocketbase › discussions › 6282
How to convert image data from $http response to base64 image · pocketbase/pocketbase · Discussion #6282
January 13, 2025 - onRecordCreateRequest(async (e) => { const avatar = e.record.get('avatar') try { const res = $http.send({ url: avatar, }) if (res.statusCode == 200) { // Need to implement convert_to_base64() function logic const base64 = convert_to_base64(res.raw) e.record.set('avatar', base64) } } catch (err) { console.log('request failed', err) } e.next() }, 'members') ... If creating a base64 string from the response.raw doesn't work then you can try to fetch the url content as raw bytes using $filesystem.fileFromURL helper to avoid the conversion from Go->JS strings, for example: const file = $filesystem.fileFromURL(YOUR_URL) const encoded = "data:image/png;base64," + Buffer.from(file.reader.bytes).toString("base64") console.log(encoded)
Author: pocketbase
🌐
Postman
community.postman.com › help hub
How to convert local image into base64 encoding - Help Hub - Postman Community
December 6, 2023 - I am using API to create test execution with evidence attaching as well. So, used prerequiste tab to generate base64 encoded which used in data in evidence tag. I am facing issues in prerequiste script. unable to uploa…
🌐
Base64.Guru
base64.guru › home › developers › javascript › examples
Convert image to Base64 in JavaScript | Examples | JavaScript | Developers | Base64
To convert image to Base64 and get the original Base64 string, I highly recommend using one of the following methods: Encode remote file to Base64 in JavaScript · Encode form file to Base64 in JavaScript · Of course, we can use new Image() to draw a canvas and using the toDataURL() method ...
🌐
n8n
community.n8n.io › tips & tricks
Converting a base64 string to a JPG - Tips & Tricks - n8n Community
November 3, 2025 - This took me a short while to figure out. I’ve been vibe coding with the new Google AI Studio. When a user uploads an image and that image is posted to N8N, it is in the format:- “data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEC…..” If you then want to get the actual file, you would use ...
🌐
Jam
jam.dev › utilities › base64-to-image
Base64 to Image Converter | Free, Open Source & Ad-free
Base64 encoding converts binary image data into ASCII text, making it safe to transmit over text-based protocols like HTTP, email, and JSON. This is commonly used for embedding small images directly in HTML, CSS, or JavaScript without requiring separate HTTP requests.
🌐
Medium
medium.com › @scriptingwithcharles › converting-image-file-to-base64-without-undefined-in-javascript-ba2c12f270e1
Converting Image/File to BASE64 without “undefined” in JavaScript | by Charles | Medium
September 11, 2025 - fileGrabber.addEventListener("change",(e)=>{ const base64 = convertImageToBase64(e.target.files[0]); display.textContent = base64; }) Now go to your browser and try this out.
🌐
Appfarm Community
community.appfarm.io › bug reports
Base64 string to Image object - Bug reports - Appfarm Community
March 1, 2024 - Good evening, I might be getting quite late here, but I’m struggling with getting my base64 string to be converted to a png image. I believe it worked earlier this evening, but now it suddenly is not able to create an image. I have stripped the solution down to the exact base64 png string ...