我试图只将动画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的第一帧转换为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
参数中设置的文件的文件内容。