Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary image loaded from server to image with javascript

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

like image 356
Marc Avatar asked Dec 10 '12 19:12

Marc


1 Answers

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

like image 99
Paul S. Avatar answered Oct 27 '22 19:10

Paul S.