javascript 从图像中获取像素颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17789076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get pixel color from an image
提问by Eitan
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.
我想获得图像颜色的左上角像素(坐标:0,0),无论图像是否旋转。
How can I do that, using javascript or php code?
我该怎么做,使用 javascript 或 php 代码?
回答by Louis Ricci
- 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)
- You want just the top left so
- 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
anda
values.
- The array will have
- 创建画布文档.createElement
- 获取二维上下文
canvas.getContext('2d')
- 将图像绘制到画布上
context.drawImage(image, x, y)
- 确保图像来自同一域,否则您将无法访问其像素
- 获取图像的像素数据
context.getImageData(x1, y1, x2, y2)
- 你只想要左上角所以
context.getImageData(0, 0, 1, 1)
- 你只想要左上角所以
- getImageData 的结果将在其
data
字段中包含一个像素数组(context.getImageData(0,0,1,1).data
)- 该阵列将有
r
,g
,b
和a
的值。
- 该阵列将有
回答by Eitan
For an image on a browser you can't use PHP unless you can transfer the image to a server first.
对于浏览器上的图像,您不能使用 PHP,除非您可以先将图像传输到服务器。
n the browser, if you can draw the image in a canvas
you could use the getImageData()
method:
在浏览器中,如果您可以在 a 中绘制图像,则canvas
可以使用以下getImageData()
方法:
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.
您必须允许任何旋转 - 大概您知道应用了什么旋转。