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

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 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据