如何从图像中获取像素的x,y坐标颜色? [英] How to get a pixel's x,y coordinate color from an image?

查看:858
本文介绍了如何从图像中获取像素的x,y坐标颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法可以检查PNG图像的选定点(x,y)是否透明? 解析方案

根据杰夫的回答,你的第一步就是创建一个PNG的画布表示。下面创建一个离屏画布,其宽度和高度与图像相同,并在其上绘制图像。

  var img = document.getElementById('my-image'); 
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d')。drawImage(img,0,0,img.width,img.height);

之后,当用户点击时,使用 event.offsetX event.offsetY 来获取头寸。这可以用来获取像素:

  var pixelData = canvas.getContext('2d')。getImageData(event。 offsetX,event.offsetY,1,1).data; 

由于您只抓取一个像素,因此pixelData是包含像素的R,G, B和A值。对于alpha,任何小于255的值都表示某种透明度级别,0表示完全透明。



以下是一个jsFiddle示例: http://jsfiddle.net/thirtydot/9SEMf/869/ 为方便起见,我使用了jQuery,但这绝不是必需的。


$ b

注意: getImageData 属于浏览器的同源策略,以防止数据泄漏,这意味着这种技术如果您使用来自其他域的图像或(我相信,但某些浏览器可能已经解决此问题)来自任何域的SVG,则会失败。这可以防止站点为登录用户提供自定义图像资源并且攻击者想要读取图像以获取信息。您可以通过提供来自同一台服务器的图像或实现跨源资源共享来解决问题。


Is there any way to check if a selected(x,y) point of a PNG image is transparent?

解决方案

Building on Jeff's answer, your first step would be to create a canvas representation of your PNG. The following creates an off-screen canvas that is the same width and height as your image and has the image drawn on it.

var img = document.getElementById('my-image');
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

After that, when a user clicks, use event.offsetX and event.offsetY to get the position. This can then be used to acquire the pixel:

var pixelData = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;

Because you are only grabbing one pixel, pixelData is a four entry array containing the pixel's R, G, B, and A values. For alpha, anything less than 255 represents some level of transparency with 0 being fully transparent.

Here is a jsFiddle example: http://jsfiddle.net/thirtydot/9SEMf/869/ I used jQuery for convenience in all of this, but it is by no means required.

Note: getImageData falls under the browser's same-origin policy to prevent data leaks, meaning this technique will fail if you dirty the canvas with an image from another domain or (I believe, but some browsers may have solved this) SVG from any domain. This protects against cases where a site serves up a custom image asset for a logged in user and an attacker wants to read the image to get information. You can solve the problem by either serving the image from the same server or implementing Cross-origin resource sharing.

这篇关于如何从图像中获取像素的x,y坐标颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆