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(){
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.
Kaiido May 10 '16 at 5:45 a.m. 2016-05-10 05:45
source share