简体   繁体   中英

Get base64 of an image

I am trying to get base64 of the image in my HTML by using HTML FileReader but for some reasons it doesn't work. My html is:

<div></div>

And script is:

var file = "http://mw2.google.com/mw-panoramio/photos/medium/23830229.jpg";
var reader = new FileReader();
reader.onload = function (e) {
    iconBase64 = e.target.result;
    $('div').append(iconBase64);
}

Can anybody help me?

I'll have to go against the majority and tell that you can actually get it without a canvas.

The statement that FileReader can't read external files is not completely true :
You can give it a blob as source.
So you can convert your external resource to a Blob object, using XMLHttpRequest
making it available from the local machine so the above statement isn't completely false either ,
then get its dataURL from the FileReader.

 var file = "http://mw2.google.com/mw-panoramio/photos/medium/23830229.jpg"; var xhr = new XMLHttpRequest(); xhr.onload = function(e) { getDataURL(this.response); }; xhr.open('GET', file, true); // the magic part xhr.responseType = 'blob'; xhr.send(); function getDataURL(blob) { var reader = new FileReader(); reader.onload = function(event) { var dataURL = this.result; document.querySelector('img').src = dataURL; document.querySelector('p').innerHTML = dataURL; }; var source = reader.readAsDataURL(blob); } 
 <img/> <p></p> 

You can't use FileReader to solve this problem, because you are not trying to read local files (that is the purpose of FileReader)

Just convert the image taken from the web link using something like this answer https://stackoverflow.com/a/20285053/912450

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM