我正在尝试仅将动画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以填充卸载的部分它设法加载了什么。那么,在将它作为PNG之前,如何才能完全加载GIF?
答案 0 :(得分:1)
我会使用ImageMagick的convert
将GIF的第一帧转换为PNG。您可以通过将[0]
添加到文件名来解决第一帧问题。
哦,最新版本的convert
可以直接处理源文件位置的URI:
convert "http://imgur.com/a.gif[0]" a.png
或
convert "http://imgur.com/a.gif[0]" -thumbnail 128x128 a.png
答案 1 :(得分:0)
您应该使用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
参数中设置的文件的文件内容。