检查图像的像素数据

时间:2012-12-12 03:27:45

标签: javascript

让我们说:

Img = new Image();
img.src = 'test.png';

有没有办法检查该图像中的像素x= 10; y = 16;并返回其RGBA数据?或者您是否必须创建像素阵列以查询特定像素...我不确定在您设置图像src时是否创建了像素阵列?

1 个答案:

答案 0 :(得分:3)

您必须先将其绘制到<canvas>。这仅在图像来自同一个域(在您给出的示例中)

时才有效
img = new Image();
img.src = "test.png";
img.onload = function() {
  var c = document.createElement('canvas'), d, img = this;
  if( c.getContext) {
    c.width = img.width;
    c.height = img.height;
    c = c.getContext("2d");
    c.drawImage(img,0,0);
    d = c.getImageData(0,0,img.width,img.height);
    img.getPixel = function(x,y) {
      return d.slice((y*img.width+x)*4,4);
    };
  }
  else {
    // canvas not supported, fall back
    img.getPixel = function(x,y) {return [0,0,0,0];}
  }
};

然后你可以调用图像上的函数:

alert(img.getPixel(10,16));
// alerts something like 190,255,64,255