Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an image has transparency using GD?

How do I check if an image has transparent pixels with php's GD library?

like image 657
HappyDeveloper Avatar asked Mar 31 '11 04:03

HappyDeveloper


People also ask

How can you tell if an image is transparent?

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.

How do you know if a GIF has a transparent background?

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.

Is PNG transparent BG?

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.

Which image types can have transparency?

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.


1 Answers

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.

like image 190
Javier Parra Avatar answered Sep 18 '22 04:09

Javier Parra