Using raw image data from ajax request for data URI Using raw image data from ajax request for data URI ajax ajax

Using raw image data from ajax request for data URI


Thanks for that. I've done a bit more digging on this and it turns out there is a solution at least on current versions of Firefox and Chrome (EDIT: IE10 works too). You can use XMLHttpRequest2 and use a typed array (Uint8Array). The following code works:

<!DOCTYPE html><html><head><script type='text/javascript'>function init(){    var xmlHTTP = new XMLHttpRequest();    xmlHTTP.open('GET','/images/photos/badger.jpg',true);    // Must include this line - specifies the response type we want    xmlHTTP.responseType = 'arraybuffer';    xmlHTTP.onload = function(e)    {        var arr = new Uint8Array(this.response);        // Convert the int array to a binary string        // We have to use apply() as we are converting an *array*        // and String.fromCharCode() takes one or more single values, not        // an array.        var raw = String.fromCharCode.apply(null,arr);        // This works!!!        var b64=btoa(raw);        var dataURL="data:image/jpeg;base64,"+b64;        document.getElementById("image").src = dataURL;    };    xmlHTTP.send();}</script></head><body onload='init()'><img id="image" alt="data url loaded image" /></body></html>

Basically you ask for a binary response, then create an 8-bit unsigned int view of the data before converting it back into a (binary-friendly) string String.fromCharCode(). The apply is necessary as String.fromCharCode() does not accept an array argument. You then use btoa(), create your data url and it then works.

The following resources were useful for this:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays?redirectlocale=en-US&redirectslug=JavaScript%2FTyped_arrays

and

http://www.html5rocks.com/en/tutorials/file/xhr2/

Nick


Nick's answer works very well. But when I did this with a fairly large file, I got a stack overflow on

var raw = String.fromCharCode.apply(null,arr);

Generating the raw string in chunks worked well for me.

var raw = '';var i,j,subArray,chunk = 5000;for (i=0,j=arr.length; i<j; i+=chunk) {   subArray = arr.subarray(i,i+chunk);   raw += String.fromCharCode.apply(null, subArray);}


I had trouble with the ArrayBuffer -> String -> Base64 method described above, but ran across another method using Blob that worked great. It's not a way to convert raw data to Base 64 (as in the title), but it is a way to display raw image data (as in the actual question):

var xhr = new XMLHttpRequest();xhr.responseType = 'arraybuffer';xhr.onload = function() {    var blb = new Blob([xhr.response], {type: 'image/png'});    var url = (window.URL || window.webkitURL).createObjectURL(blb);    image.src = url;}xhr.open('GET', 'http://whatever.com/wherever');xhr.send();

All credit goes to Jan Miksovsky, author of this fiddle. I just stumbled across it and thought it'd make a useful addition to this discussion.