【发布时间】:2012-02-03 22:07:15
【问题描述】:
我正在使用 GD 库自动生成上传图像的缩略图版本。我调用适当的image____() 函数以与原始格式相同的格式保存。我的代码适用于 JPEG 和 GIF,但如果我上传 PNG 文件,生成的缩略图无效。它实际上只包含 33 个字节(到目前为止我尝试过的任何源 PNG)。此图像不显示在浏览器中,也无法通过 Preview(在 MacOS 上)打开。
我使用 imagecreatetruecolor() 和 imagecopyresampled() 来生成缩略图,如下所示:
function _resizeImageToFit($resource, $size)
{
$sourceWidth = imagesx($resource);
$sourceHeight = imagesy($resource);
if($sourceWidth >= $sourceHeight) {
// landscape or square
$newHeight = 1.0*$size/$sourceWidth*$sourceHeight;
$newWidth = $size;
}
else {
// portrait
$newWidth = 1.0*$size/$sourceHeight*$sourceWidth;
$newHeight = $size;
}
$thmb = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($thmb, $resource, 0, 0, 0, 0, $newWidth, $newHeight, $sourceWidth, $sourceHeight);
return $thmb;
}
以下是我的设置的版本信息(它是 MAMP 版本 1.9.4)
PHP 版本 5.3.2 GD版捆绑(2.0.34兼容)
以下是生成的无效缩略图 (PNG) 示例:
âPNGIHDRdaØMì∞
【问题讨论】:
-
这个函数的返回值怎么办?保存到文件系统还是直接提供?
-
我打电话给
$saveSuccess = $imagesave($thumbResource, $thumbPath, 100);,然后是imagedestroy($thumbResource);。我在这里根据图像类型使用一个变量来调用图像函数。当这是一个 PNG 时,调用最终为imagepng()。 $saveSuccess(imagepng 返回的值)设置为 TRUE 表示成功,即使图像已损坏。