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

使用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

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;
}