【发布时间】:2012-02-04 12:36:48
【问题描述】:
您知道 GIF 文件支持动画,但 GIF 图像不一定必须有动画。
有没有办法使用 php 或 java 来检查 GIF 图片是否有动画?
谢谢。
【问题讨论】:
标签: java php gif animated-gif
您知道 GIF 文件支持动画,但 GIF 图像不一定必须有动画。
有没有办法使用 php 或 java 来检查 GIF 图片是否有动画?
谢谢。
【问题讨论】:
标签: java php gif animated-gif
imagecreatefromgif() 函数的 php 手册页中有一段简短的 sn-p 代码,应该是您需要的:
<?php
function is_ani($filename)
{
$filecontents=file_get_contents($filename);
$str_loc=0;
$count=0;
while ($count < 2) # There is no point in continuing after we find a 2nd frame
{
$where1=strpos($filecontents,"\x00\x21\xF9\x04",$str_loc);
if ($where1 === FALSE)
{
break;
}
else
{
$str_loc=$where1+1;
$where2=strpos($filecontents,"\x00\x2C",$str_loc);
if ($where2 === FALSE)
{
break;
}
else
{
if ($where1+8 == $where2)
{
$count++;
}
$str_loc=$where2+1;
}
}
}
if ($count > 1)
{
return(true);
}
else
{
return(false);
}
}
exec("ls *gif" ,$allfiles);
foreach ($allfiles as $thisfile)
{
if (is_ani($thisfile))
{
echo "$thisfile is animated<BR>\n";
}
else
{
echo "$thisfile is NOT animated<BR>\n";
}
}
?>
如果需要,可以很容易地修改它来计算帧数。
【讨论】:
这是一个小的 PHP 脚本,它应该能够确定图像是否是动画 gif。我已经对其进行了测试,它对我有用。
<?php
$img="your_image";
$file = file_get_contents($img);
$animated=preg_match('#(\x00\x21\xF9\x04.{4}\x00\x2C.*){2,}#s', $file);
if ($animated==1){
echo "This image is an animated gif";
} else {
echo "This image is not an animated gif";
}
?>
只需将 $img 变量编辑为您想要测试的任何图像(例如 image.gif、image.jpg)。
【讨论】:
试试这样的:
public function getNumFramesFromGif(string $url): int{
$image = file_get_contents($url);
$imagick = new \Imagick();
$imagick->readImageBlob($image);
$numFrames = $imagick->identifyFormat("%n"); //https://www.php.net/manual/en/imagick.identifyformat.php https://davidwalsh.name/detect-gif-animated
return $numFrames;
}
如果它返回 1,则不是动画。
如果不依赖像 Imagick 这样的库,我会谨慎编写函数,因为像 this 这样的“陷阱”。
【讨论】: