dongqiao3214 2012-03-09 02: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 02: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部