I want to be able to detect whether an image is transparent or not using the Imagick PHP extension.
So far, the only luck I've been having is to run the exec() / some other command, and use the ImageMagick command line tool to achieve this. Here's what I mean:
exec("identify -verbose example_transparent_image.png | grep \"Alpha\"", $output);
$is_transparent = !empty($output) ? true : false;
The logic is simple. Do a verbose check on the image in question: if the output contains any alpha information, that means it uses transparency.
It seems that the PHP imagick extension should have this as one of its commands, but the lack of documentation is killing me. It seems silly to have to run this kind of check each time.
Ahhh, solved (I think). Imagick has a function getImageAlphaChannel() which returns true if it contains any alpha information and false if it doesn't.
Make sure you have ImageMagick 6.4.0 or newer.
http://www.php.net/manual/en/function.imagick-getimagealphachannel.php
Maybe this
http://ru.php.net/manual/en/function.imagick-identifyimage.php
What's about this?
substr((new Imagick($FILE))->identifyImage()['type'], 0, -5) == 'Alpha'
look at the documentation of identifyImage. You will notice the missing documentation of the functions output. It's just a parsed version of
identify -verbose $FILE (from the imagick package)
where type
identifies the image's type (compare source).
You can see that imagick returns the value from some MagickTypeOptions
array which is defined here. This array contains an -Alpha and -Matte version for every image type if it's color palette contains alpha.
Theoretically you could save an image with such palette without using it, but every decent programm should swith to the non-alpha version in this case. But false positives are possible but should be rare.
Also I don't check for the -Matte image types because in the array is defined in a way that for every image type constant there are two entries with different names (-Alpha and -Matte), but as -Alpha comes first this name will be returned for that image type.