Html image blob to base64

I have some problems with fileinputjs.Src images are blob.But I want to use src images to do something. Therefore, I use readAsDataURL to get base64. But there are some problems with this.

<script type="text/javascript"> $("#last").click(function(){ var blob=document.querySelector(".file-preview-image").src; var reader = new FileReader(); //้€š่ฟ‡ FileReader ่ฏปๅ–blob็ฑปๅž‹ reader.onload = function(){ this.result === dataURI; //base64็ผ–็  } console.log(reader.readAsDataURL(blob)); }) </script> 

Then there are Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob' .

+3
javascript image base64 blob
May 10 '16 at 5:34
source share
1 answer

There are many misconceptions.

  • Your blob variable is not a Blob , but a string, the address of .file-preview-image .
    FileReader cannot do anything from this line. (Or at least not what you want).
  • in the onload callback of FileReader , you just check if the result is equal to the undefined dataURI variable. It will do nothing.
  • you are trying to execute console.log call to readAsDataURL , which will be undefined since this method is asynchronous (you have to call console.log in the callback).

But since I assume that you have the URL of the object ( blob:// ), then your decision is to either get the real Blob object and transfer it to FileReader or draw this image on the canvas and then call its toDataURL method to get base64 encoded version.

If you can get blob:

 var dataURI; var reader = new FileReader(); reader.onload = function(){ // here you'll call what to do with the base64 string result dataURI = this.result; console.log(dataURI); }; reader.readAsDataURL(blob); 

otherwise:

 var dataURI; var img = document.querySelector(".file-preview-image"); var canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; canvas.getContext('2d').drawImage(img, 0,0); dataURI = canvas.toDataURL(); 

But note that for a later time, you will have to wait for your image to load before you can draw it on canvas.
In addition, by default it will convert your image to a png version. You can also pass image/jpeg as the first parameter toDataURL('image/jpeg') if the source image is in JPEG format.
If the image is svg, then there will be another solution using the <object> element, but if you really need it, I will leave it for another answer.

+9
May 10 '16 at 5:45
source share



All Articles