12

I'm loading a jpeg image from my server in binary format via XMLHttpRequest (I need it that way). It's not base64 encoded.

Is it possible to turn it to an img object with javascript?

Thanks

1 Answer 1

6

If the character encoding of the XMLHttpRequest has been set to something that won't change the binary data, or you've set the response type, you can then run .responseText through btoa (putting it in base64 and letting you assign it as a data URI) or access .response for the binary data, respectively.


Assuming your instance is named xhr and you're using the charset method before xhr.send but after xhr.open do

xhr.overrideMimeType("text/plain; charset=x-user-defined");

then when you're 200 OK

var dataURI = 'data:image/jpeg;base64,' + btoa(xhr.responseText);

Which you can then set as a src of an <img>.


Again assuming xhr, this time .response method; between .open and .send,

xhr.responseType = "arraybuffer";

Then at 200 OK

var arrayBufferView = new Uint8Array(xhr.response), // can choose 8, 16 or 32 depending on how you save your images
    blob = new Blob([arrayBufferView], {'type': 'image\/jpeg'}),
    objectURL = window.URL.createObjectURL(blob);

Which you can then set as a src of an <img>. Example

Sign up to request clarification or add additional context in comments.

4 Comments

This is called an inline image. Note that IE8 only supports inline images that are less than 32 KB (for the base64 encoded data, so the source image would have to be less than 24 KB), and IE7 and earlier don't support inline images at all (if that matters).
Tried that, but btoa(xhr.responseText) keeps returning Error: INVALID_CHARACTER_ERR: DOM Exception 5. I cannot find why this happens. For IE7/IE8... I will have to make a Flash object to deal with it grrr
@Marc that happens because btoa has some bugs (same/similar also applies to webkit), I'll update answer with an ArrayBuffer -> Blob -> through URL.createObjectURL method, which in my opinion is slightly better than through FileReader but still not as nice as btoa.
As for the compatibility of this method, looks like IE10+

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.