10

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.

Scott
  • 101
  • 1
  • 3

3 Answers3

10

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

Scott
  • 111
  • 2
  • 3
    Having run into this exact problem myself, I ran through both identifyimage and getimagealphachannel. Identifyimage simply doesn't provide sufficient information, while getimagealphachannel worked just fine. Theoretically, getImageAlphaChannel() provides a ALPHACHANNEL constant, but the documentation is, frankly, garbage in this respect. I get a '0' for a JPG, a '1' for a PNG with alpha, and a '0' for a 32-bit with no alpha. Basically, perfectly expected results. So, even though this is current a 10-month-old Question/Answer, I thought it was worth adding in my 2 cents. – John Green Apr 30 '12 at 21:19
0

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.

Hoffmann
  • 1,050
  • 9
  • 26
0

Maybe this

http://ru.php.net/manual/en/function.imagick-identifyimage.php

azat
  • 3,545
  • 1
  • 28
  • 30