简体   繁体   English

如何使用XMLHttpRequest(XHR2)获取下载PNG的像素数据

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

I am using this code from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data 我使用的代码来自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. 我用它来下载一个png文件,然后我想在Canvas元素中显示它。 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? 我意识到有更简单的方法可以做到这一点,但我需要能够操作像素,所以我真的想在TypedArray中使用像素数据,我也尝试使用常规DOM Image对象加载它,将其绘制到canvas和使用getImageData()但它太慢(它是一个大图像) - 所以现在我正在尝试这种方法,我从负载得到的是我所假设的压缩数据,所以我的问题是 - 有一个快速的方法解压缩/膨胀这些数据以获取图像像素数据,或者我只是错误地试试这个?

you can make a base64 and set to src of a image... like below 你可以创建一个base64并设置为图像的src ...如下所示

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/ 一个工作的jsfiddle ...... - > http://jsfiddle.net/Castrolol/mHv4b/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM