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):



  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 用matlab写代码
  • ¥30 motoradmin系统的多对多配置
  • ¥15 求组态王串口自定义通信配置方法或代码?
  • ¥15 实验 :UML2.0 结构建模
  • ¥20 用vivado写数字逻辑实验报告撰写,FPGA实验
  • ¥15 为什么shp文件会有这种小方块?
  • ¥15 ecplise在连接数据库时显示加载驱动成功但是数据库连接失败
  • ¥15 visionmaster启动失败,提示为“机器不满足授权而被禁用”
  • ¥15 IDEA中圈复杂度如何具体设置
  • ¥50 labview采集不了数据