phpgifphp-gd

How to check if a GIF has transparency using GD?


I found the question How to check if an image has transparency using GD? but the the answers are all for PNG files. Is there a solution for checking if a GIF image has transparency in PHP using the GD extension?


Solution

  • I am assuming that:

    On that basis, the following code will load a GIF and check that no palette entry contains transparency - rather than checking every single pixel in a very slow double loop over height and width of an image:

    <?php
    
    function GIFcontainstransparency($fname){
    
       // Load up the image
       $src=imagecreatefromgif($fname);
    
       // Check image is palettised
       if(imageistruecolor($src)){
          fwrite(STDERR,"ERROR: Unexpectedly got a truecolour (non-palettised) GIF!");
       }
    
       // Get number of colours - i.e. number of entries in palette
       $ncolours=imagecolorstotal($src);
    
       // Check palette for any transparent colours rather than all pixels - to speed it up
       for($index=0;$index<$ncolours;$index++){
          $rgba = imagecolorsforindex($src,$index);
          if($rgba['alpha']>0){
             return true;
          }
       }
       return false;
    }
    
    ////////////////////////////////////////////////////////////////////////////////
    // main
    ////////////////////////////////////////////////////////////////////////////////
    
       if(GIFcontainstransparency("image.gif")){
          echo "Contains transparency";
       } else {
          echo "Is fully opaque";
       }
    ?>