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

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法