'imagecolorat' 和透明度

8

如何获取图像中像素的透明度值?

'imagecolorat'只能选择图像中指定位置像素的颜色索引。通过该索引,我可以获取RGB值,但无法获取透明度值。

希望您能理解,谢谢。

3个回答

14

解决方案可能如下:

$colorIndex = imagecolorat($img, $x, $y);
$colorInfo = imagecolorsforindex($img, $colorIndex);
print_r($colorInfo);

这将会打印出类似下面的东西:

Array
(
   [red] => 226
   [green] => 222
   [blue] => 252
   [alpha] => 0
)

其中[alpha]是您的透明度值...(从0到127,其中0是完全不透明,127是完全透明)

享受吧!


嗯,我以为 alpha 值是从 0 到 255,0 表示透明,255 表示不透明。 - user889030

11
据我所知,透明度的值是由函数imagecolorat返回的。您可以尝试:
$color        = imagecolorat($image, $x, $y);
$transparency = ($color >> 24) & 0x7F;

透明度是0到127之间的整数,因此我们需要屏蔽32位颜色整数的前8个比特。


哦,谢谢!我不知道imagecolorat实际上包含alpha值。 - Roman
1
请注意,第四个字节是用于透明度而非不透明度。因此,0 表示完全不透明,而 127 表示完全透明。在其他环境中,这可能会被反转,例如在 CSS 中,其中 0.0 表示完全透明,而 1.0 表示完全不透明。 - Marten Koetsier
一个32位的值有多大?因为imagecolorat函数返回了16777215。 - Edward

1
根据PHP手册,imagecolorat返回指定X/Y坐标处颜色的索引(我假设这是针对GIF和/或PNG-8的)。
如果您知道索引,则问题在于确定文件中哪个索引是透明的。
imagecolortransparent可能值得一看,imagecolorsforindex也可能有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接