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
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
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