如何使用 GD 检查 GIF 是否具有透明度?

How to check if a GIF has transparency using GD?

我看到 this thread 并且解决方案非常有效,但仅适用于 PNG。在 PHP-GD 中是否有检查 GIF 图像是否具有透明度的解决方案?

此代码创建 gif 预览并检查透明度

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

与其他格式相比,我对 GIF 不太熟悉,因此我的假设可能不正确。如果我错了,请告诉我 - 一个简单的评论,而不是否决票,我们将不胜感激。

我假设:

  • 所有 GIF 都已调色,
  • 对于任何透明的调色板条目,alpha 分量都将是非零(可能是 127),
  • 编码器不会不必要地添加透明调色板条目。

在此基础上,以下代码将加载 GIF 并检查是否没有调色板条目包含透明度 - 而不是检查图像高度和宽度的非常缓慢的双循环中的每个像素:

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