drfals1307 2012-08-21 16:06
浏览 360

将动画GIF转换为PNG

I'm trying to display only the first frame of an animated GIF to a PNG to use as a thumbnail. I currently have this code:

<?php
function myImageCreateFromGif($file_or_url) { 
$dummy_file = "/tmp/dummy.gif"; 
# if this is a url, use fopen to get the file data, then 
# save it to a dummy file 
if (preg_match("/(http|ftp):\/\//i", $file_or_url)) { 
        # open the file using fopen, which supports remote URLs 
        $input = fopen($file_or_url, "rb"); 
        # read the contents of the file 
        # will accept files up to 10Mb, but will probably get 
        # and EOF before that, we have to do it this way because 
        # filesize isn't designed to work with URLs.  sigh. 
        $image_data = fread($input, 10000000); 
        fclose($input); 
        # write the contents to a dummy file 
        $output = fopen("$dummy_file", "wb"); 
        fwrite($output, $image_data); 
        fclose($output); 
        # create the gif from the dummy file 
        $image = ImageCreateFromGif($dummy_file); 
        # get rid of the dummy file 
        unlink($dummy_file); 
    } 
    # if it's not a URL, we can simply open the image directly 
    else { 
        $image = ImageCreateFromGif($file_or_url); 
    } 
    if ($image) { return $image; } 
    else { return 0; } 
}
$image = "http://i.imgur.com/".$_GET["i"].".gif";
$img = myImageCreateFromGif($image);
if($img) {
    header("Content-Type: image/png");
    ImagePNG($img);
    ImageDestroy($img);
}
?>

Which works fine, but the GIF does not fully load before it becomes a PNG, so the page returns either a broken image if the GIF could not load at all, or a partially-loaded GIF that fills the unloaded part by repeating what it has managed to load. So, how can I get the GIF to load completely before making it a PNG?

  • 写回答

2条回答 默认 最新

  • du6jws6975 2012-08-21 16:13
    关注

    I would use ImageMagick's convert to transform the first frame of the GIF into PNG. You address the first frame by adding [0] to the filename.

    Oh, and recent versions of convert can directly handle URIs for source file locations just well:

     convert  "http://imgur.com/a.gif[0]"  a.png
    

    or

     convert  "http://imgur.com/a.gif[0]"  -thumbnail  128x128  a.png
    
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题