dqk42179
2011-03-15 00:55
浏览 157
已采纳

使用GD2将png转换为jpg ..透明度问题

I have an image.png with white background and some trasparceny over it.

I tried this to convert the image into jpg:

$data = file_get_contents('image.png');
$resource = imagecreatefromstring($data);
imagejpeg($resource); //> I TRIED WITH QUALITY = 100 TOO

Problem is where the png got the trasparency now the jpg got a pretty huge black zone. This is how jpg looks:

http://img861.imageshack.us/img861/20/context.jpg

Any way to solve the problem?

Edit1:

As suggested by Abiusx I tried this too:

$data = file_get_contents('image.png');
$resource = imagecreatefromstring($data);
imagealphablending($data, false);
imagesavealpha($data, true);
imagejpeg($resource);

But the result was the same. Please note The source .png image is:


(source: tipradar.com)

Thanks to Patrick comment: here the trick: GD! Converting a png image to jpeg and making the alpha by default white and not black

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doujiao3074 2011-03-15 13:50
    已采纳
    点赞 打赏 评论
  • doujia1988 2011-03-15 01:28

    This is the function I use to resize a PNG but preserve transparency, if it doesnt help, tell me to extract the parts necessary for you:

    function Resize($ImageFile,$OriginalFile)
    {
        $ext=basename($OriginalFile);
        $ext=explode(".",$ext);
        $ext=array_pop($ext);
        $ext=strtolower($ext);
        if ($ext=="jpg" or $ext=="jpeg" or $ext=="jpe")
            $img=imagecreatefromjpeg($ImageFile);
        elseif ($ext=="png")
            $img=imagecreatefrompng($ImageFile);
        elseif ($ext=="gif")
            $img=imagecreatefromgif($ImageFile);
        else
            return false;
        list($w,$h)=getimagesize($ImageFile);
        $dstimg=imagecreatetruecolor(140,100);
    
        imagealphablending($dstimg, false);
        imagecopyresampled($dstimg,$img,0,0,0,0,140,100,$w,$h);
        imagesavealpha($dstimg, true);
        imagepng($dstimg,$ImageFile);
        return true;
    }
    
    点赞 打赏 评论

相关推荐