繁体   English   中英

将GIF动画转换为PNG

[英]Convert animated GIF to PNG

我正在尝试仅将动画GIF的第一帧显示为PNG以用作缩略图。 我目前有以下代码:

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

效果很好,但是GIF在变成PNG之前没有完全加载,因此如果GIF根本无法加载,页面将返回损坏的图像,或者通过重复已加载的内容来部分填充GIF来填充未加载的部分设法加载。 那么,如何在将GIF制作为PNG之前完全加载它?

我将使用ImageMagick的convert GIF的第一帧convert为PNG。 通过在文件名上添加[0]来寻址第一帧。

哦,最新版本的convert可以很好地直接处理源文件位置的URI:

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

要么

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

您应该使用perl通过http检索文件。

这来自php手册: http : //www.php.net/manual/de/function.curl-exec.php

/**
 * Send a GET requst using cURL
 * @param string $url to request
 * @param array $get values to send
 * @param array $options for cURL
 * @return string
 */
function curl_get($url, array $get = NULL, array $options = array())
{   
    $defaults = array(
        CURLOPT_URL => $url. (strpos($url, '?') === FALSE ? '?' : ''). http_build_query($get),
        CURLOPT_HEADER => 0,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_TIMEOUT => 4
    );

    $ch = curl_init();
    curl_setopt_array($ch, ($options + $defaults));
    if( ! $result = curl_exec($ch))
    {
        trigger_error(curl_error($ch));
    }
    curl_close($ch);
    return $result;
} 

它将返回您在$url参数中设置的文件的文件内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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