Get pixel color from an image

落花浮王杯 提交于 2019-11-27 04:15:47

问题


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?


回答1:


  • 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.



回答2:


For an image on a browser you can't use PHP unless you can transfer the image to a server first.

n the browser, if you can draw the image in a canvas you could use the getImageData() method:

var myImg = new Image();
myImg.src = 'image.jpg';
var context = document.getElementById('canvas').getContext('2d');
context.drawImage(myImg, 0, 0);
var data = context.getImageData(x, y, 1, 1).data;

You'd have to allow for any rotation - presumably you know what rotation has been applied.



来源:https://stackoverflow.com/questions/17789076/get-pixel-color-from-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!