我正在尝试仅将动画 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 之前让它完全加载呢?