Search

4/09/2012

handle binary image data

BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
window.URL = window.URL || window.webkitURL;

var req = new XMLHttpRequest();
req.open('get', url + '?size=' + size, true);
req.responseType = 'arraybuffer'; //  "text", "arraybuffer", "blob", or "document"

req.onload = function () {
  var bb = new BlobBuilder();
  bb.append(this.response); // append raw image response
  var blob = bb.getBlob('image/jpeg');
  var url = window.URL.createObjectURL(blob); // create a time url for this image, ex: blob:http://abdb-f12a-asd-sdg
}

via: New Tricks in XMLHttpRequest2 - HTML5 Rocks ArrayBuffer responses With this new awesomeness, we can rework the previous example, but this time, fetch the image as an ArrayBuffer instead of a string. Handing the buffer over to the BlobBuilder API creates a Blob:
BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;

var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png', true);
xhr.responseType = 'arraybuffer';

xhr.onload = function(e) {
  if (this.status == 200) {
    var bb = new BlobBuilder();
    bb.append(this.response); // Note: not xhr.responseText

    var blob = bb.getBlob('image/png');
    ...
  }
};

xhr.send();
An ArrayBuffer is a generic fixed-length container for binary data. They are super handy if you need a generalized buffer of raw data, but the real power behind these guys is that you can create "views" of the underlying data using JavaScript typed arrays. In fact, multiple views can be created from a single ArrayBuffer source. For example, you could create an 8-bit integer array that shares the same ArrayBuffer as an existing 32-bit integer array from the same data. The underlying data remains the same, we just create different representations of it. If you want to work directly with a Blob and/or don't need to manipulate any of the file's bytes, use xhr.responseType='blob'
window.URL = window.URL || window.webkitURL;  // Take care of vendor prefixes.

var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png', true);
xhr.responseType = 'blob';

xhr.onload = function(e) {
  if (this.status == 200) {
    var blob = this.response;

    var img = document.createElement('img');
    img.onload = function(e) {
      window.URL.revokeObjectURL(img.src); // Clean up after yourself.
    };
    img.src = window.URL.createObjectURL(blob);
    document.body.appendChild(img);
    ...
  }
};

xhr.send();

沒有留言: