How to get the pixel data of an PNG downloaded using XMLHttpRequest (XHR2)

2.3k views Asked by At

I am using this code from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

var oReq = new XMLHttpRequest();
oReq.open("GET", "/myfile.png", true);
oReq.responseType = "arraybuffer";

oReq.onload = function (oEvent) {
  var arrayBuffer = oReq.response; // Note: not oReq.responseText
  if (arrayBuffer) {
    var byteArray = new Uint8Array(arrayBuffer);
    for (var i = 0; i < byteArray.byteLength; i++) {
      // do something with each byte in the array
    }
  }
};

oReq.send(null);

I am using it to download a png file which I then want to display in a Canvas element. I realise there are easier ways to do this, but I need to be able to manipulate the pixels so I would really like to have the pixel data in a TypedArray, also I have tried loading it using a regular DOM Image object, drawing it to canvas and using getImageData() but it too slow (it's a large image) - so now I am trying this method, what I get from the load is what I assume is the compressed data, so my question is - is there a quick way to decompress/inflate this data to get the image pixel data, or am I just plain wrong to try this?

1

There are 1 answers

1
Luan Castro On BEST ANSWER

you can make a base64 and set to src of a image... like below

var oReq = new XMLHttpRequest();
oReq.open("GET", "https://npmjs.org/static/npm.png", true);
oReq.responseType = "arraybuffer";

oReq.onload = function (oEvent) {

  var arrayBuffer = oReq.response; // Note: not oReq.responseText
  var binaryString = '';

  if (arrayBuffer) {

    var byteArray = new Uint8Array(arrayBuffer);

    for (var i = 0; i < byteArray.byteLength; i++) {

      binaryString += String.fromCharCode( byteArray [ i ] ); //extracting the bytes

    }

    var base64 = window.btoa( binaryString ); //creating base64 string


    img.src = "data:image/png;base64," + base64; //creating a base64 uri

  }
};

oReq.send(null);

a working jsfiddle... -> http://jsfiddle.net/Castrolol/mHv4b/