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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:38:33  来源:igfitidea点击:

Get pixel color from an image

javascriptimagepixel

提问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)
  • The result of getImageData will have an array of pixels in it's datafield (context.getImageData(0,0,1,1).data)
    • The array will have r, g, band avalues.
  • 创建画布文档.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
    • 该阵列将有rgba的值。

回答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 canvasyou 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.

您必须允许任何旋转 - 大概您知道应用了什么旋转。