How do I check if an image has transparent pixels with php's GD library?
Images that have transparency often illustrate it by using a gray and white checkered pattern. The idea is that you can see which parts of the image will be transparent before you save it. The checkered pattern is the background. There's no transparency.
The best way I know is to test if the alpha channel has a mean=0. A fully transparent image has an alpha channel that is totally black.
If you are using a screenshot or a PNG image, it will default to have a transparent background. If you are using a JPG or other file format, you'll need to adjust your background color in the Snagit editor first or it will default to white rather than transparent.
Transparency. The GIF and PNG formats also both support transparency. If you need any level of transparency in your image, you must use either a GIF or a PNG. GIF images (and also PNG) support 1-color transparency.
I know this is old, but I just found this on the comments of the PHP docs. (link)
Here is the function which determines whether the PNG image contains alpha or not:
<?php function is_alpha_png($fn){ return (ord(@file_get_contents($fn, NULL, NULL, 25, 1)) == 6); } ?>
The color type of PNG image is stored at byte offset 25. Possible values of that 25'th byte is:
- 0 - greyscale
- 2 - RGB
- 3 - RGB with palette
- 4 - greyscale + alpha
- 6 - RGB + alpha
Only works for PNG images though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With