Learn how to verify if an image has transparency with Imagick in PHP.

The first thing you may think to verify wheter an image has transparency or not is to verify the format of the file. The raster file formats that support transparency are GIF, PNG, BMP, TIFF, and JPEG 2000, through either a transparent color or an alpha channel. But, in the same way that they can have transparency, they may haven't too. Therefore the method of verification through the format of the image isn't enough to verify what you need.

In this article we'll show you how to verify properly if an image has transparency or not with Imagick in PHP.

Verify transparency

To check if an image has transparency or not, you can use the getImageAlphaChannel method of Imagick. This method returns an integer identified as the constant of the colorspace of the image (check the colorspace constants of image for more info). 

For us is interesting the Undefined Colorspace constant that means that the image has no transparency. This constant has a value of 0 if the image has no transparency, so you can check it with an if statement easily:

<?php

// Create instance of an image
$image = new Imagick();

$image->readImage("your_image.png");

// 0 = No transparency
// 1 = Has transparency
$hasTransparency = $image->getImageAlphaChannel();

if($hasTransparency){
    echo "The image has transparency :)";
}else{
    echo "The image has no transparency :(";
}

If you want to verify the transparency with the constant instead, you can do it easily:

<?php

// Create instance of the Watermark image
$image = new Imagick();

$image->readImage("your_image.png");

// 0 = No transparency
// 1 = Has transparency
$hasTransparency = $image->getImageAlphaChannel();

if($image->getImageAlphaChannel() == Imagick::COLORSPACE_UNDEFINED){
    echo "The image has no transparency :(";
}else{
    echo "The image has transparency !";
}

If the alpha channel result isn't 0 or 1, then the image has another colorspace that you can identify with the following breakout:

Constants:
0 - UndefinedColorspace    
1 - RGBColorspace    
2 - GRAYColorspace    
3 - TransparentColorspace    
4 - OHTAColorspace    
5 - LABColorspace    
6 - XYZColorspace    
7 - YCbCrColorspace    
8 - YCCColorspace    
9 - YIQColorspace    
10 - YPbPrColorspace    
11 - YUVColorspace    
12 - CMYKColorspace    
13 - sRGBColorspace    
14 - HSBColorspace    
15 - HSLColorspace    
16 - HWBColorspace

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors