Dandan
Dandan

Reputation: 11

How to get Blob from local image URL?

I have local image URL and I want to get the blob from it.

The only way I found was to do HTTP request 'get' on the local URL, and read the returned blob... but this is such a strange way.

The code snippet using HTTP:

 function readBody(xhr) {
    var data;
    if (!xhr.responseType || xhr.responseType === "text") {
        data = xhr.responseText;
    } else if (xhr.responseType === "document") {
        data = xhr.responseXML;
    } else {
        data = xhr.response;
    }
    return data;
}

var xhr=new XMLHttpRequest();
xhr.open('GET',results[i],true);
xhr.responseType='blob';
xhr.send();
xhr.onreadystatechange=function()
{
    var blob;
    if(xhr.readyState==4)
    {
        blob=readBody(xhr);
        uploadPhoto(blob,storageRef);

    }
};

Upvotes: 0

Views: 3203

Answers (1)

Pixelomo
Pixelomo

Reputation: 6737

Your image needs to be converted to base64 and then from base64 in to binary. This is done using .toDataURL() and dataURItoBlob()

It's pretty fiddly process, I've created a tutorial you can follow which walks you through the process.

Upvotes: 1

Related Questions