PHP的imagepng()方法保存了无效的图像

Seb*_*tin 1 php gd

我正在使用GD库自动生成上传图像的缩略图版本.我调用相应的image____()函数以与原始格式相同的格式保存.我的代码适用于JPEG和GIF,但如果我上传PNG文件,则生成的缩略图无效.它实际上只包含33个字节(到目前为止我已尝试过任何源PNG).此图像不会显示在浏览器中,也不能通过预览(在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;
}
Run Code Online (Sandbox Code Playgroud)

以下是我的设置的版本信息(它的MAMP版本1.9.4)

捆绑的PHP版本5.3.2 GD版本(兼容2.0.34)

以下是无效生成的缩略图(PNG)的示例:

APNG

IHDRdaØMì∞

Seb*_*tin 7

我发现了我的错误.imagepng()的质量值范围为0到9,而imagejpeg()的取值范围为0到100,而imagegif()不接受任何此类参数.我试图保存质量为100的PNG.

所以,这是一个可爱的RTM案例.谢谢你的回复.

http://ca3.php.net/manual/en/function.imagepng.php

http://ca3.php.net/manual/en/function.imagejpeg.php

http://ca3.php.net/manual/en/function.imagegif.php