Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check pixel data of an image

Tags:

javascript

Lets say i have:

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

Is there a way to check a pixel from that image say x= 10; y = 16; And return its RGBA data back ? Or do you have to create the pixel array to enquire a specific pixel... I'm unsure if the pixel array is created when you setup the image src or not ?

like image 233
Sir Avatar asked Oct 22 '22 22:10

Sir


1 Answers

You have to draw it to a <canvas> first. This will only work if the image is from the same domain (which it is in the example you gave)

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];}
  }
};

Then you can call the function on the image:

alert(img.getPixel(10,16));
// alerts something like 190,255,64,255
like image 125
Niet the Dark Absol Avatar answered Nov 13 '22 03:11

Niet the Dark Absol