Get pixel color from an image

Eitan picture Eitan · Jul 22, 2013 · Viewed 39.9k times · Source

I have an image on a browser.

I want to get the top left pixel of the image color (at coordinates: 0,0), no matter whether the image is rotated or not.

How can I do that, using javascript or php code?

Answer

Louis Ricci picture Louis Ricci · Jul 22, 2013
  • Create a canvas document.createElement
  • Get the 2d context canvas.getContext('2d')
  • Draw the image to the canvas context.drawImage(image, x, y)
    • Make sure the image is from the same domain or you won't have access to its pixels
  • Get the pixel data for the image context.getImageData(x1, y1, x2, y2)
    • You want just the top left so context.getImageData(0, 0, 1, 1)
  • The result of getImageData will have an array of pixels in it's data field (context.getImageData(0,0,1,1).data)
    • The array will have r, g, b and a values.