Reputation: 1417
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?
Upvotes: 0
Views: 440
Reputation: 137113
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>
Upvotes: 2
Reputation: 7207
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
Upvotes: 0