726

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
coderslay
  • 13,960
  • 31
  • 73
  • 121

20 Answers20

1174

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:

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:


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)" />
Miquel
  • 8,339
  • 11
  • 59
  • 82
HaNdTriX
  • 28,732
  • 11
  • 78
  • 85
  • Are you sure you are using IE11? I just tested it in IE11 and it worked fine for me. But I also tested it in IE10 and I got a security error because IE10 doesn't support CORS for images. You might have to proxy your images through your own domain in order to make it work in IE10. – HaNdTriX Apr 29 '14 at 08:01
  • When i try to use this the GIF image will still say this in itsbase64 form: data:image/png;base64................ they should say image/gif. I tried passing image/gif in outputFormat var variable by getting the image format but still it shows data:image/png...Why is this so? – maths Jun 12 '14 at 01:52
  • The GIF format is not supported as an output format. More info @ https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement#Methods (I updated my answer to clarify this point) – HaNdTriX Jun 12 '14 at 08:24
  • Is there a way to do this without jquery as the callback? – Doge Jul 07 '14 at 10:37
  • This function has nothing to do with jQuery. This is an async operation so you need a callback or some kind of [promise](http://www.html5rocks.com/en/tutorials/es6/promises/?redirect_from_locale=de). – HaNdTriX Jul 07 '14 at 11:55
  • 80
    Not working in chrome for me: `Image from origin **** has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.` – DickieBoy Aug 05 '14 at 09:19
  • What version of chrome are you using? Did you try the fiddle above? – HaNdTriX Aug 05 '14 at 13:34
  • @DickieBoy It depends on the configuration of the server hosting the image. The JSFiddle works with the image http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png because its server has allowed fiddle.jshell.net access. Read more at http://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work – Fuhrmanator Aug 09 '14 at 13:01
  • @Fuhrmanator I tried the fiddle. That was the error I got, could be that the server has changed its configuration. – DickieBoy Aug 12 '14 at 09:03
  • 7
    Just in case this trips anyone else up, this routine includes the "data:image/jpg;base64," header in the string it returns, so you don't need to append that. – Chris Rae Jan 16 '15 at 21:02
  • @Chris R Thanks for pointing that out. I admit the function name was not as descriptive, as it should have been. – HaNdTriX Jan 16 '15 at 22:23
  • Also, if you try to create a very large canvas on iOS (e.g. one from the camera, in my case) this will appear to work fine but return "data:,". You can fix this by changing the canvas width and height to something smaller, e.g. 100, and modifying the read call to something like ctx.drawImage(img, 0, 0, 100, 100). – Chris Rae Jan 21 '15 at 20:35
  • is this lossless? like, same as base64_encode(file_get_contents($url)) of PHP? or will the canvas conversion mess with it? – hanshenrik Mar 06 '15 at 02:25
  • This script won't work follow HTTP 301 Mover Permanently Location: http://new/location.jpg ; should fix that or add a warning. that's (probably) why the code example above isn't working for people, they don't change the url, and that url now redirects to http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png – hanshenrik Mar 06 '15 at 02:29
  • 2
    Warnin2: something messes with the content. somewhere along the way, there's a chance the data gets corrupted/altered (even though, perhaps not by much), at least that happens for me on firefox 35 on some images, the base64 is different from the base64 that php creates on the same image. – hanshenrik Mar 06 '15 at 02:39
  • 2
    Yes that is right. Some data might get lost since we actually draw the image to a canvas Element (https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage) and then convert it to a dataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL). – HaNdTriX Mar 06 '15 at 09:12
  • Is there a way to make this work for image saved on a local file system e.g. `file://C:/test.jpg` – malifa Jun 23 '15 at 10:34
  • No thats not possible, because you won't have access to the local file system. But you can use the fileReader API. Check out this fiddle http://jsfiddle.net/handtrix/xztfbx1m/ – HaNdTriX Jun 23 '15 at 10:57
  • How second approach could support file type?! – DaNeSh Nov 11 '15 at 21:48
  • @DaNeSh You could encode videos or audio files as well as image files. e.g.: http://jsfiddle.net/handtrix/YvQ5y/1730/ – HaNdTriX Nov 12 '15 at 14:28
  • 3
    Approach: FileReader (2) works more quickly than approach Canvas. Tested on big photos. Hope it will be helpfull for some one. – Max Dec 24 '15 at 06:07
  • Try this image! Not working https://qph.is.quoracdn.net/main-thumb-t-309833-200-3fIVdqGbgAIn8d5LaTub5mBWPsKkd2iC.jpeg – asingh Mar 22 '16 at 11:02
  • Yepp thats because it is blocked by the server via CORS. http://www.html5rocks.com/en/tutorials/cors/ – HaNdTriX Mar 22 '16 at 12:15
  • If someone wants to use ES6 try this gist: https://gist.github.com/HaNdTriX/bdffd11761701fbeba27f23e9a69515f – HaNdTriX Mar 29 '16 at 19:44
  • I was using approach 1 but had to comment out the "img.crossOrigin = 'Anonymous';" line in order to make it work in IE (11). I was getting 302 errors from IIS and all the images I was trying to download were reported as "Aborted" in the network tab of the IE Developer Console. – brz Mar 30 '16 at 10:58
  • 1
    FYI: IE11 throws InvalidStateError upon setting responseType. Workaround: Set responseType after calling open() for this to work in IE11. https://connect.microsoft.com/IE/feedback/details/795580/ie11-xmlhttprequest-incorrectly-throws-invalidstateerror-when-setting-responsetype – Jeff Ward Jan 31 '17 at 23:31
  • @HaNdTriX Hi, could you explain why judge 'img.complete === undefined'?It is for compatibility? – SmallTown NE Jan 29 '18 at 07:06
  • This makes sure, that the load event also fires for cached images. https://gist.github.com/HaNdTriX/7704632 – HaNdTriX Jan 29 '18 at 07:22
  • If the complete api is not supported it will be undefined. – HaNdTriX Jan 30 '18 at 08:31
  • @HaNdTriX .. Can you give a code, for the same using axios..? I am working with reactjs. – ArunValaven Mar 19 '18 at 12:25
  • No, but here is a hint to point you in the right direction. Use axios responseType prop. – HaNdTriX Mar 21 '18 at 12:51
  • Thanks for the detailed answer. Option #2 seems to be missing the `outputFormat` argument in the example invocation of `toDataURL`. – Crashalot Mar 18 '19 at 00:00
  • Do you know if the FileReader approach suffers from any data-loss issues like the canvas approach? Thanks again! – Crashalot Mar 18 '19 at 00:02
  • The outputFormat is optional. Better omit it. I just added it for completeness. Afaik `FileReader` doesn't suffer from any data loss. I compared its output with other implementations (e.g. http://php.net/manual/en/function.base64-decode.php). – HaNdTriX Mar 18 '19 at 07:50
  • @DickieBoy in order to allow local resources you can use something like [live-server](https://www.npmjs.com/package/live-server). – Miquel Mar 04 '23 at 21:29
231

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).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 3
    Does `toDataURL` give control over the callbacks such as `done/fail/always` as is the case for xhr? – Jeroen Ooms Feb 04 '14 at 22:34
  • Can we extract 2 or more canvas as a single PNG? – techie_28 Jul 11 '16 at 11:48
  • 18
    This approach fails in the case of CORS violation. Apart from that, this solution should address the question. – Revanth Kumar Apr 04 '17 at 19:01
  • Here is [npm package for it](https://www.npmjs.com/package/canvas_image_processing) – user3517175 Oct 09 '18 at 14:56
  • @RevanthKumar everything fails in CORS violation, depending on if your image comes from a cross-origin server, but if it does, and if you're able to load it as a blob url, then there's no problem. If the image is being loaded in an `` tag from a cross-domain source, then there are reasons why we can't get the bytes anyways. Any case where u can get the bytes, you can get a data URL, and in any of those cases you can write to a canvas – B''H Bi'ezras -- Boruch Hashem Jun 03 '20 at 05:02
  • 2
    we all know that converting binary to base64 takes up more data, but using canvas in this way to get base64 can increase it even more if you don't use `reader.readAsDataURL` since you probably will also loose all image compression when using toDataURL. that's unless you want every image to be converted to a specific format. when you use the canvas you also loose all metadata like: EXIF, rotation, camera, geolocation etc – Endless Jul 20 '20 at 11:19
  • Instructions unclear. Tried to copy paste this answer, got `You: function not found`. – lmat - Reinstate Monica Jul 22 '21 at 19:20
101

This snippet can convert your string, image and even video file to Base64 string data.

<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<script type='text/javascript'>
  function encodeImageFileAsURL() {

    var filesSelected = document.getElementById("inputFileToLoad").files;
    if (filesSelected.length > 0) {
      var fileToLoad = filesSelected[0];

      var fileReader = new FileReader();

      fileReader.onload = function(fileLoadedEvent) {
        var srcData = fileLoadedEvent.target.result; // <--- data: base64

        var newImage = document.createElement('img');
        newImage.src = srcData;

        document.getElementById("imgTest").innerHTML = newImage.outerHTML;
        alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
        console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
      }
      fileReader.readAsDataURL(fileToLoad);
    }
  }
</script>
Neithan Max
  • 11,004
  • 5
  • 40
  • 58
  • 5
    Not only is it great, this also bypasses the crossdomain origin problem! With this, you can allow users to supply their own images or images from an URL (since Windows will fetch it on its own), draw them on the canvas, and work with them while still being able to use .toDataURL() etc. Thanks a lot! – ElDoRado1239 Nov 16 '14 at 16:35
  • Hello, how can this be applied to an image loaded from a remote url without facing cross domain issues? Thanks – guthik Jul 17 '18 at 15:12
  • This works sometimes in Chrome 78.0.3904.97, but other times it crashes the tab. – Dshiz Nov 11 '19 at 05:44
49

Basically, if your image is

<img id='Img1' src='someurl'>

then you can convert it like

var c = document.createElement('canvas');
var img = document.getElementById('Img1');
c.height = img.naturalHeight;
c.width = img.naturalWidth;
var ctx = c.getContext('2d');

ctx.drawImage(img, 0, 0, c.width, c.height);
var base64String = c.toDataURL();
Paul Clark
  • 61
  • 1
  • 14
mehmet mecek
  • 2,615
  • 2
  • 21
  • 25
  • 8
    Unfortunately this will only work for local images, if you try it useing a remote image (choose one from the web) it writes this to (firefox) console: 'SecurityError: The operation is insecure'. – user2677034 Jan 23 '18 at 21:15
  • 3
    It may work on other images but depends on the CORS settings of that site and must be specified as `` – Mike Dec 15 '18 at 11:01
  • On Firefox you can temporarily disable that security. Goto "about:config" and change property "privacy.file_unique_origin" to false – Manuel Romeiro Feb 19 '20 at 13:38
27

Here is what I did:

// Author James Harrington 2014
function base64(file, callback){
  var coolFile = {};
  function readerOnload(e){
    var base64 = btoa(e.target.result);
    coolFile.base64 = base64;
    callback(coolFile)
  };

  var reader = new FileReader();
  reader.onload = readerOnload;

  var file = file[0].files[0];
  coolFile.filetype = file.type;
  coolFile.size = file.size;
  coolFile.filename = file.name;
  reader.readAsBinaryString(file);
}

And here is how you use it

base64( $('input[type="file"]'), function(data){
  console.log(data.base64)
})
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
James Harrington
  • 3,138
  • 30
  • 32
25

I found that the safest and reliable way to do it is to use FileReader().

Demo: Image to Base64

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <body>
    <input id="myinput" type="file" onchange="encode();" />
    <div id="dummy">
    </div>
    <div>
      <textarea style="width:100%;height:500px;" id="txt">
      </textarea>
    </div>
    <script>
      function encode() {
        var selectedfile = document.getElementById("myinput").files;
        if (selectedfile.length > 0) {
          var imageFile = selectedfile[0];
          var fileReader = new FileReader();
          fileReader.onload = function(fileLoadedEvent) {
            var srcData = fileLoadedEvent.target.result;
            var newImage = document.createElement('img');
            newImage.src = srcData;
            document.getElementById("dummy").innerHTML = newImage.outerHTML;
            document.getElementById("txt").value = document.getElementById("dummy").innerHTML;
          }
          fileReader.readAsDataURL(imageFile);
        }
      }
    </script>
  </body>
</html>

UPDATE - THE SAME CODE WITH COMMENTS FOR @AnniekJ REQUEST:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <body>
    <input id="myinput" type="file" onchange="encode();" />
    <div id="dummy">
    </div>
    <div>
      <textarea style="width:100%;height:500px;" id="txt">
      </textarea>
    </div>
    <script>
      function encode() {
        // Get the file objects that was selected by the user from myinput - a file picker control
        var selectedfile = document.getElementById("myinput").files;
        // Check that the user actually selected file/s from the "file picker" control
        // Note - selectedfile is an array, hence we check it`s length, when length of the array
        // is bigger than 0 than it means the array containes file objects
        if (selectedfile.length > 0) {
          // Set the first file object inside the array to this variable
          // Note: if multiple files are selected we can itterate on all of the selectedfile array  using a for loop - BUT in order to not make this example complicated we only take the first file object that was selected
          var imageFile = selectedfile[0];
          // Set a filereader object to asynchronously read the contents of files (or raw data buffers) stored on the            user's computer, using File or Blob objects to specify the file or data to read. 
          var fileReader = new FileReader();
          // We declare an event of the fileReader class (onload event) and we register an anonimous function that will be executed when the event is raised. it is "trick" we preapare in order for the onload event to be raised after the last line of this code will be executed (fileReader.readAsDataURL(imageFile);) - please read about events in javascript if you are not familiar with "Events" 
          fileReader.onload = function(fileLoadedEvent) {
            // AT THIS STAGE THE EVENT WAS RAISED
            // Here we are getting the file contents - basiccaly the base64 mapping
            var srcData = fileLoadedEvent.target.result;
            // We create an image html element dinamically in order to display the image
            var newImage = document.createElement('img');
            // We set the source of the image we created
            newImage.src = srcData;
            // ANOTHER TRICK TO EXTRACT THE BASE64 STRING
            // We set the outer html of the new image to the div element
            document.getElementById("dummy").innerHTML = newImage.outerHTML;
            // Then we take the inner html of the div and we have the base64 string
            document.getElementById("txt").value = document.getElementById("dummy").innerHTML;
          }
          // This line will raise the fileReader.onload event - note we are passing the file object here as an argument to the function of the event  
          fileReader.readAsDataURL(imageFile);
        }
      }
    </script>
  </body>
</html>
Jonathan Applebaum
  • 5,738
  • 4
  • 33
  • 52
  • Hi, I was looking for a way to convert images in my Powerpoint AddIn to base64 (because otherwise I can't add them into slides) and found your response. Could you maybe explain to me a bit more what you are doing here? I am fairly new to this so I don't really get the whole FileReader. Just to give some background: I have a string selectedImages, which are .png's, and I want to convert them to base64 files and then be able to add them to a powerpoint slide. – AnniekJ Nov 09 '20 at 16:16
  • @AnniekJ please see my updated answer with the comment above each line of code – Jonathan Applebaum Nov 09 '20 at 16:56
11

If you have a file object, this simple function will work:

function getBase64 (file, callback) {

    const reader = new FileReader();

    reader.addEventListener('load', () => callback(reader.result));

    reader.readAsDataURL(file);
}

Usage example:

getBase64(fileObjectFromInput, function(base64Data){
    console.log("Base64 of file is", base64Data); // Here you can have your code which uses Base64 for its operation, // file to Base64 by oneshubh
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shubham
  • 1,740
  • 1
  • 15
  • 17
  • If I send reader.result in request body to WebAPI, would I be able to consume it using byte[] type on api end? – CredibleAshok May 21 '21 at 05:55
  • try `reader.readAsArrayBuffer(file)` it gives you byte array https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsArrayBuffer if you are using java, the base64 can be converted to byte array there, follow the sample https://stackoverflow.com/questions/41935207/base64-string-to-byte-in-java – Shubham May 22 '21 at 13:34
9

I ended up using a function that returns a Promise.

const getImg64 = async() => {
  const convertImgToBase64URL = (url) => {
  console.log(url)
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.crossOrigin = 'Anonymous';
      img.onload = () => {
          let canvas = document.createElement('CANVAS')
          const ctx = canvas.getContext('2d')
          canvas.height = img.height;
          canvas.width = img.width;
          ctx.drawImage(img, 0, 0);
          const dataURL = canvas.toDataURL();
          canvas = null;
          resolve(dataURL)
      }
      img.src = url;
    })
  }
  //for the demonstration purposes I used proxy server to avoid cross origin error
  const proxyUrl = 'https://cors-anywhere.herokuapp.com/'
  const image = await convertImgToBase64URL(proxyUrl+'https://image.shutterstock.com/image-vector/vector-line-icon-hello-wave-260nw-1521867944.jpg')
  console.log(image)
}
getImg64()

You can use this approach in any async function. Then you can just await for the converted image and continue with instructions.

Jakub A Suplicki
  • 4,586
  • 1
  • 23
  • 31
8
uploadProfile(e) {

    let file = e.target.files[0];
    let reader = new FileReader();

    reader.onloadend = function() {
        console.log('RESULT', reader.result)
    }
    reader.readAsDataURL(file);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mahedi Hasan Durjoy
  • 1,031
  • 13
  • 17
8

Here is the way you can do with Javascript Promise.

const getBase64 = (file) => new Promise(function (resolve, reject) {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject('Error: ', error);
})

Now, use it in event handler.

const _changeImg = (e) => {
        const file = e.target.files[0];
        let encoded;
        getBase64(file)
          .then((result) => {
            encoded = result;
           })
          .catch(e => console.log(e))
    }
Bhuwan Adhikari
  • 879
  • 1
  • 9
  • 21
5

As far as I know, an image can be converted into a Base64 string either by FileReader() or storing it in the canvas element and then use toDataURL() to get the image. I had the similar kind of problem you can refer this.

Convert an image to canvas that is already loaded

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ajeet Lakhani
  • 3,768
  • 2
  • 22
  • 37
5

You could use FileAPI, but it's pretty much unsupported.

bks
  • 1,886
  • 1
  • 24
  • 43
Artem Tikhomirov
  • 21,497
  • 10
  • 48
  • 68
4

Try this code:

For a file upload change event, call this function:

$("#fileproof").on('change', function () {
    readImage($(this)).done(function (base64Data) { $('#<%=hfimgbs64.ClientID%>').val(base64Data); });
});

function readImage(inputElement) {
    var deferred = $.Deferred();

    var files = inputElement.get(0).files;

    if (files && files[0]) {
        var fr = new FileReader();
        fr.onload = function (e) {
            deferred.resolve(e.target.result);
        };
        fr.readAsDataURL(files[0]);
    } else {
        deferred.resolve(undefined);
    }

    return deferred.promise();
}

Store Base64 data in hidden filed to use.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ravi polara
  • 564
  • 3
  • 14
  • 1
    Hi Ravi! I see you are relatively new. Unless the original poster specifically asks for a library solution such as jQuery, lodash and so on, it's better for everyone to answer using the bare minimums, in this case, plain javascript. If you still want to contribute with jQuery, please make it abundantly clear in your entry :) – Neithan Max Mar 16 '19 at 16:13
3

In the case you are facing cors origin error, there is a simple proxy called cors-fix that loads the image on server and return it as buffer array.

Therefore, we can use fetch to get the image data and filereader to convert it to dataUrl, as described by @HaNdTriX.

  function toDataUrl(url) {
    fetch(`https://cors-fix.web.app/v1?url=${url}`)
    .then(data => data.blob().then(blob => {
      const reader = new FileReader();

      reader.onloadend = () =>  {
        console.log(reader.result);
      };

      reader.onerror = () => {
        console.log('reader error');
      };

      reader.readAsDataURL(blob);
    }));
  }
Esdras Vitor
  • 161
  • 1
  • 5
2

document.querySelector('input').onchange = e => {
  const fr = new FileReader()
  fr.onloadend = () => document.write(fr.result)
  fr.readAsDataURL(e.target.files[0])
}
<input type="file">
井上智文
  • 1,905
  • 17
  • 14
2

Needed to leverage reader to convert blob to base64, prefer to use async-await syntax so I chose to extract reader logic into helper like this:

//* Convert resBlob to base64
export const blobToData = (blob: Blob) => {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result)
    reader.readAsDataURL(blob)
  })
}

and calling it using await in main code:

//* Convert resBlob to dataUrl and resolve
const resData = await blobToData(resBlob)
Chukwuemeka Maduekwe
  • 6,687
  • 5
  • 44
  • 67
1

Assuming that you are doing this in a browser:

With await:

import axios from 'axios'

const response = await axios.get(url, { responseType: 'blob' });
return window.URL.createObjectURL(response.data);

With promise

import axios from 'axios'

const response = await axios.get(url, { responseType: 'blob' })
  .then((response) => {
    const dataUrl = window.URL.createObjectURL(response.data);
    // do something with your url
  });
Žilvinas Rudžionis
  • 1,954
  • 20
  • 28
  • This is such an underestimated comment! I have been struggling with all kinds of errors returned when using manual btoa, TextEncoder, etc... This is *the* answer when axios is used. Life can be so easy! – OGordo Mar 14 '23 at 18:27
0

Well, if you are using Dojo Toolkit, it gives us a direct way to encode or decode into Base64.

Try this:

To encode an array of bytes using dojox.encoding.base64:

var str = dojox.encoding.base64.encode(myByteArray);

To decode a Base64-encoded string:

var bytes = dojox.encoding.base64.decode(str);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vikash Pandey
  • 5,407
  • 6
  • 41
  • 42
  • 2
    @DownVoter - Dear its better to point out error also if you are marking something negative. so that someone can improve. as far as I am understanding dojo in also an JavaScript library then if you are allowed to use dojo, you can definitely use this approach. – Vikash Pandey Oct 09 '17 at 08:52
0

You can also simply extract base-64 only part of the URL by ding this:

var Base64URL = canvas.toDataURL('image/webp')
var Base64 = Base64URL.split(",")[1] //Returns the base64 part
Vinnie Amir
  • 557
  • 5
  • 10
0

This is very simple. 1> Just call the function and pass your image. 2> Save the return value and use wherever required.

//call like this
const convertedFile = await imageToBase64(fileObj);
console.log("convertedFile",convertedFile);

//this is the required function

 async function  imageToBase64(image) {
 const reader = new FileReader();
 reader.readAsDataURL(image);
 const data= await new Promise((resolve, reject) => {

   reader.onload = () => resolve(reader.result);

   reader.onerror = error => reject(error);

  });
return data;
}

export default imageToBase64;
MD ALI
  • 13
  • 2