Angelo Joseph Salvador
Angelo Joseph Salvador

Reputation: 352

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?

Upvotes: 0

Views: 948

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207798

I am assuming that:

  • all GIFs are palettised,
  • the alpha component will be non-zero (probably 127) for any palette entry which is transparent,
  • encoders do not add transparent palette entries unnecessarily.

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";
   }
?>

Upvotes: 2

  Delf
Delf

Reputation: 113

This code create preview for gifs and check transparency

$width=64;
$height=64;
$src='original.gif';
$dst='preview.gif';
list($width_orig, $height_orig) = getimagesize($src);

$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromgif($src);

$transparent_index = imagecolortransparent($image);
$palette_colors_cnt = imagecolorstotal($image);
if ($transparent_index >= 0) {
    imagepalettecopy($image, $image_p);
    imagefill($image_p, 0, 0, $transparent_index);
    imagecolortransparent($image_p, $transparent_index);
    imagetruecolortopalette($image_p, true, $palette_colors_cnt);
}
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagegif($image_p, $dst);

Upvotes: 0

Related Questions