title: Using raw image data from ajax request for data URI
body: <p>I'm trying to use a combination of Ajax and data URIs to load a JPEG image and extract its EXIF data with a single HTTP request. I am modifying a library (<a href="https://github.com/kennydude/photosphere">https://github.com/kennydude/photosphere</a>) to do this; currently this library uses two HTTP requests to set the source of the image and to get the EXIF data.</p>
  
  <p>Getting the EXIF works, no problem. However I am having difficulty using the raw data from the ajax request as source for the image.</p>
  
  <p>Source code for a small test of the technique:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;script type='text/javascript'&gt;
  
  function init()
  {
      // own ajax library - using it to request a test jpg image
      new Ajax().sendRequest
      (
          "/images/photos/badger.jpg",
           { method : "GET",
              callback: function(xmlHTTP)
              {
  
                  var encoded = btoa (unescape(encodeURIComponent(xmlHTTP.responseText)));
                  var dataURL="data:image/jpeg;base64,"+encoded;
  
                  document.getElementById("image").src = dataURL;
              }
          }
      );
  }
  
  &lt;/script&gt;
  &lt;script type="text/javascript" src="http://www.free-map.org.uk/0.6/js/lib/Ajax.js"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body onload='init()'&gt;
  &lt;img id="image" alt="data url loaded image" /&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>I get what looks like sensible jpeg data sent back, and the length (in bytes) of the raw data and the base64-encoded-then-unencoded-again raw data is the same. However the attempt to set the image src fails on both Firefox (25) and Chrome (31) (current versions) - chrome displays "broken image" icon suggesting the src is an invalid format. </p>
  
  <p>I used this mozilla page for info on base64 encoding/decoding:</p>
  
  <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding</a></p>
  
  <p>Any idea what might be wrong? Looking around I can create the base64 encoded image server side but can it be done client side like this? For one thing, base64 encoding server side obviously increases the data size and the whole purpose of this exercise is to cut down the amount of data being transferred from the server, as well as the number of requests.</p>
  
  <p>Thanks,
  Nick</p>