简体   繁体   中英

How to check if a GIF has transparency using GD?

I saw this thread and the solutions perfectly works but for PNG only. Is there a solution for checking if a GIF image has transparency in PHP-GD?

I am less familiar with GIF s than other formats, so my assumptions may be incorrect. Please let me know if I am wrong - a simple comment, rather than a down-vote, would be appreciated.

I am assuming that:

  • all GIF s 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";
   }
?>

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM