How can I convert image binary from API call to data URI in Javascript?

Luke picture Luke · Dec 6, 2011 · Viewed 12.6k times · Source

The Google API I'm using is transmitting images only as binary data.

I have absolutly no idea how to put this into a data URI to display it, thanks for any help!

The call I'm talking about is this API call.

As you can see, it says:

The server returns bytes of the photo.

For the call (it's an extension), I use the chrome_ex_oauth methods. Maybe I need to add something into the header to get real binary data, not string as it comes in right now...

What I need to do is to convert the resulting binary into data URI so I can display it.


Ok, I get this out of the XHR request

enter image description here

Now, I dont know binary stuff much. This is somehow encoded binary data i assume? I tried to put this into btoa and other base64 encoders, everything throws an error. I tried to overrideMimeType with different things and the "response" changed in some strange ways, but nothing accepts the data.

So now I have this code:

var nxhr = new XMLHttpRequest();
nxhr.onreadystatechange = function (data) {
    if (nxhr.readyState == 4) {
        console.log(nxhr);
    }
};
nxhr.open(method, url, true);
nxhr.setRequestHeader('GData-Version', '3.0');
nxhr.setRequestHeader('Authorization', oauth.getAuthorizationHeader(url, method, params));
nxhr.send('Data to send');

Anybody else has any idea how to get this for me not understandable response into a data uri???

Thanks for any help

Answer

user613857 picture user613857 · Dec 18, 2011

After conducting some tests, here is my answer:

To simply display the image using the <img> tag, you must first encode the result binary with Base64. You can do this in two different ways:

  1. Using Javascript: Use a Base64 encoder function, such as this one. After you encode the result binary data, you can display the image using the <img> tag like so: <img src="data:image/*;base64,[BASE64 ENCODED BINARY]" />. You must replace [BASE64 ENCODED BINARY] with the actual encoded binary of the image. I'm assuming you already know how to change HTML element attributes through Javascript, it's fairly easy to put the encoded binary into the src attribute of the <img> tag.

  2. Using PHP (my personal preference): Once you submit a GET request to the API, it will return you the binary. Simply use the PHP base64_encode() function.

    <img src="data:image/*;base64,<?php echo base64_encode($result); ?>" />

Where, the $result variable is what you get from the API call. You can use the PHP cURL library.

I hope this helps.