如何检查图像的特定像素是否透明? [英] How to check if a specific pixel of an image is transparent?

查看:158
本文介绍了如何检查图像的特定像素是否透明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以检查 PNG 图像的选定 (x,y) 点是否透明?

解决方案

根据 Jeff 的回答,您的第一步是创建 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.offsetXevent.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 在所有这些方面都提供了方便,但这绝不是必需的.

注意: 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.

这篇关于如何检查图像的特定像素是否透明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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