dongqiao3214 2012-03-09 10:32
浏览 192
已采纳

PHP PNG到JPG转换问题,图像失真

I have a script that uploads and resizes images using the GD library and PHP. I now want to upload a PNG image and for it to be stored as PNG and JPEG, I am then going to resize it but that's fine.

The problem I'm having is that sometimes, the converted version of the image (jpg) is distorted. Other times it is fine.

My code is taken from another answer here on StackOverflow:

function png2jpg($originalFile, $outputFile, $quality){
    $image = imagecreatefrompng($originalFile);
    imagejpeg($image, $outputFile, $quality);
    imagedestroy($image);
}

An example of the distorted result is shown below, I am fully aware that I won't get the transparency on the JPG, I just want a white background. Any ideas?

I can't post images, so link to original: http://private.granvilleoil.com/prodImages/large/Petro-Patch.png) and JPG: http://private.granvilleoil.com/prodImages/large/Petro-Patch.jpg)

  • 写回答

5条回答 默认 最新

  • dousuohe5882 2012-03-09 10:48
    关注

    You need to create a fresh image with a white (or whatever you want) background and copy the none-transparent pixels from the png to that image:

    function png2jpg($originalFile, $outputFile, $quality) {
        $source = imagecreatefrompng($originalFile);
        $image = imagecreatetruecolor(imagesx($source), imagesy($source));
    
        $white = imagecolorallocate($image, 255, 255, 255);
        imagefill($image, 0, 0, $white);
    
        imagecopy($image, $source, 0, 0, 0, 0, imagesx($image), imagesy($image));
    
        imagejpeg($image, $outputFile, $quality);
        imagedestroy($image);
        imagedestroy($source);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?