我正在尝试计算特定图像中具有透明度的像素的百分比是多少。为此,我试图检测像素是否具有透明度(在 PHP 上使用 Imagick)。我知道基本上有 'getPixel' 和 'getColor' 返回一个 rgba 数组,但是我也得到了 jpg 和非透明 png 图像的 'a' 的各种值......我已经尝试过使用和不使用标准化.
例如,对于此图像,我获得各种像素的 alpha 值 0、1、0.1、0.9 等 .
这是我正在使用的代码:
$imageIterator = $image->getPixelIterator();
foreach ($imageIterator as $row => $pixels) {
foreach ($pixels as $column => $pixel) {
$color = $pixel->getColor(true);
echo $color['a'] . PHP_EOL;
...
我做错了什么?还有其他方式获取此信息吗?
最佳答案
您可以通过以下方式检查您的版本:
php -i | grep -i -A10 magick
我的是这样的:
imagick module => enabled
imagick module version => 3.3.0
imagick classes => Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator, ImagickKernel
Imagick compiled with ImageMagick version => ImageMagick 6.9.3-0 Q16 x86_64 2016-01-08 http://www.imagemagick.org
Imagick using ImageMagick library version => ImageMagick 6.9.3-0 Q16 x86_64 2016-01-08 http://www.imagemagick.org
ImageMagick copyright => Copyright (C) 1999-2016 ImageMagick Studio LLC
ImageMagick release date => 2016-01-08
运行此代码,我得到了您图像的所有图像 - 即没有 alpha 层或完全不透明的图像:
#!/usr/local/bin/php -f
<?php
$image = new Imagick("budgie.png");
$pixel_iterator = $image->getPixelIterator();
foreach($pixel_iterator as $y => $pixels)
{
foreach($pixels as $x => $pixel)
{
$color = $pixel->getColor(true);
echo $color['a'] . PHP_EOL;
}
}
?>
同样,如果我在您的图像上运行 identify
,它会显示不存在 alpha 层:
identify -verbose budgie.png | more
Image: budgie.png
Format: PNG (Portable Network Graphics)
Mime type: image/png
Class: DirectClass
Geometry: 296x383+0+0
Units: Undefined
Type: TrueColor
Endianess: Undefined
Colorspace: sRGB
Depth: 8-bit
Channel depth:
red: 8-bit
green: 8-bit
blue: 8-bit
我认为您的版本/配置有问题。
关于php - 使用 Imagick 检测像素透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35307955/