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

问题描述 投票:0回答:2

我看到this thread和解决方案完美的工作,但仅适用于PNG。是否有解决方案来检查GIF图像在PHP-GD中是否具有透明度?

php image-processing gd php-gd
2个回答
2
投票

我对GIFs的熟悉程度低于其他格式,所以我的假设可能不正确。如果我错了,请告诉我 - 一个简单的评论,而不是一个投票,将不胜感激。

我假设:

  • 所有GIFs都是palettised,
  • 对于任何透明的调色板条目,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";
   }
?>

0
投票

此代码为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);
© www.soinside.com 2019 - 2024. All rights reserved.