doumouyi4039 2012-01-06 04:36
浏览 873
已采纳

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

I am using the GD library to automatically generate a thumbnail version of an uploaded image. I call the appropriate image____() function to save in the same format as the original. My code works fine for JPEG and GIF, but if I upload a PNG file, the resulting thumbnail is invalid. It actually only contains 33 bytes (with any source PNG that I've tried so far). This image does not display in the browser, nor can it be opened by Preview (on MacOS).

I use imagecreatetruecolor() along with imagecopyresampled() to generate the thumbnail, like this:

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;
}

Below is the version info of my setup (It's MAMP Version 1.9.4)

PHP Version 5.3.2 GD Version bundled (2.0.34 compatible)

Here is an example of an invalid generated thumbnail image (PNG):

âPNG

IHDRdaØMì∞

  • 写回答

2条回答 默认 最新

  • dsznndq4912405 2012-01-16 17:52
    关注

    I found my error. imagepng() takes a quality value range of 0 to 9, while imagejpeg() takes a range of 0 to 100 and imagegif() doesn't take any such parameter. I was trying to save a PNG with a quality of 100.

    So, this is a lovely case of RTM. Thanks for your responses.

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵