How to read binary data in IE9?

cleong picture cleong · Aug 9, 2012 · Viewed 14k times · Source

I'm working on some Javascript code that creates an alpha mask of a image using paths embedded by Photoshop. The onload handler of a IMG tag would call a clip(this). The function load the image's source file and scans through it. Here's the setup:

function clip(img) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', img.src, true);
    xhr.responseType = 'arraybuffer';
    xhr.target = img;

    xhr.onload = function(e) {
        var bytes = new Uint8Array(this.response);
        var p = findPhotoshopSegment(bytes);
        if(p) {
            var paths = parse8BIMData(bytes, p);

            /* ... replaces IMG with SVG tag ... */
        }
    };
    xhr.send();
}

You can see the code in action at http://flaczki.net46.net/JPEG/SVG.html

Currently, it only works in Firefox, Chrome, and Safari. It doesn't work in IE9. The browser supports SVG but not Uint8Array. Is there some kind of workaround?

Answer

Milan Jaric picture Milan Jaric · Aug 21, 2012

I had same issue while playing with pdf.js library, and solution I found is to make my own Uint8Array, below is code which you need. All credits goes to notmasteryet@github and full code can be found here https://gist.github.com/1057924

(function() {
  try {
    var a = new Uint8Array(1);
    return; //no need
  } catch(e) { }

  function subarray(start, end) {
    return this.slice(start, end);
  }

  function set_(array, offset) {
    if (arguments.length < 2) offset = 0;
    for (var i = 0, n = array.length; i < n; ++i, ++offset)
      this[offset] = array[i] & 0xFF;
  }

  // we need typed arrays
  function TypedArray(arg1) {
    var result;
    if (typeof arg1 === "number") {
       result = new Array(arg1);
       for (var i = 0; i < arg1; ++i)
         result[i] = 0;
    } else
       result = arg1.slice(0);
    result.subarray = subarray;
    result.buffer = result;
    result.byteLength = result.length;
    result.set = set_;
    if (typeof arg1 === "object" && arg1.buffer)
      result.buffer = arg1.buffer;

    return result;
  }

  window.Uint8Array = TypedArray;
  window.Uint32Array = TypedArray;
  window.Int32Array = TypedArray;
})();