1

我有一个白色背景的 image.png,上面有一些透明度。

我尝试将图像转换为jpg:

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

问题是png的透明度现在jpg有一个非常大的黑色区域。这是 jpg 的外观:

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

有什么办法可以解决问题吗?

编辑1:

正如 Abiusx 所建议的,我也试过这个:

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

但结果是一样的。请注意源 .png 图像是:


(来源:tipradar.com

感谢帕特里克评论:这里的诀窍:GD!将 png 图像转换为 jpeg 并使 alpha 默认为白色而不是黑色

4

2 回答 2

1

在这里回答:

GD!将 png 图像转换为 jpeg 并使 alpha 默认为白色而不是黑色

于 2011-03-15T13:50:35.527 回答
-1

这是我用来调整 PNG 大小但保留透明度的功能,如果它没有帮助,请告诉我提取您需要的部分:

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;
}
于 2011-03-15T01:28:29.637 回答