html image blob to base64

瘦欲@ 提交于 2019-12-22 10:22:29

问题


I've got some problems about to fileinputjs.The images' src are blob.But i want to use images' src to do something.So i use readAsDataURL to get base64.But there are any problems about it 。

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


回答1:


A lot of misconception here.

  • your variable blob is not a Blob, but a string, the url of .file-preview-image.
    FileReader can't do anything from this string. (Or at least not what you want).
  • in the onload callback of the FileReader, you are just checking if the result is equal to an undefined variable dataURI. That won't do anything.
  • you are trying to console.log the call to readAsDataURL which will be undefined since this method is asynchronous (you have to call console.log in the callback).

But since I guess that what you have is an object url (blob://), then your solution is either to get the real Blob object and pass it to a FileReader, or to draw this image on a canvas, and then call its toDataURL method to get a base64 encoded version.

If you can get the 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 the later, you'll have to wait that your image actually has loaded before being able to draw it on the canvas.
Also, by default, it will convert your image to a png version. You can also pass image/jpegas the first parameter of toDataURL('image/jpeg') if the original image is in JPEG format.
If the image is an svg, then there would be an other solution using the <object> element, but except if you really need it, I'll leave it for an other answer.



来源:https://stackoverflow.com/questions/37130010/html-image-blob-to-base64

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!