The source PNG image will be cropped by PHP using Imagick based on user input. The result is a cropped image that may or may not have transparent pixels. I'm looking for a way to detect if the cropped image has transparency yes or no, so I can convert opaque PNGs to JPG.
This is my code for loading the image:
// Get user input
$src = $_POST['src'];
$resize = json_decode($_POST['selection_data']);
// Load image (source image has transparency)
$dst = new Imagick($src);
// Crop image (the part that will be cropped is fully opaque)
$dst->cropImage($resize->selW, $resize->selH, $resize->selX, $resize->selY);
$dst->resizeImage($resize->dstW, $resize->dstH, imagick::FILTER_CATROM, 0.9, false);
After this, I can check the alpha channel using $dst->getImageAlphaChannel()
. But, this returns true
regardless of whether the cropped image contains any transparent pixels, because it is set while loading the source image (which has transparency).
Another way to check for transparent pixels is by looking every single pixel for an alpha value small than 1*:
$alpha = false;
for ($x = 0; $x < $resize->dstW; $x++)
{
for ($y = 0; $y < $resize->dstH; $y++)
{
if ($dst->getImagePixelColor($x, $y)->getColorValue(Imagick::COLOR_ALPHA) < 1)
{
$alpha = true;
break 2;
}
}
}
But for large images (1000x1000) it takes 30+ seconds to execute this, which is not ideal.
What is the fastest way to detect if the image has any transparent pixels?
*: Opaque pixels actually return an alpha value of 0.99999999976717 (32 bit float) on Debian Wheezy on which I'm currently testing.