PNG透明度处理在PHP中的实现

43

嗨,我在创建缩略图时遇到了一些问题,无法保持 PNG 图像的透明度。 有人有类似经验吗?任何帮助都将不胜感激。这是我目前正在做的:

$fileName= "../js/ajaxupload/tees/".$fileName;

list($width, $height) = getimagesize($fileName);

$newwidth = 257;
$newheight = 197;

$thumb = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($thumb, true);
$source = imagecreatefrompng($fileName);
imagealphablending($source, true);

imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

imagesavealpha($thumb, true);
imagepng($thumb,$newFilename);
5个回答

85

我过去用这种方法已经成功:

$thumb = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($thumb, false);
imagesavealpha($thumb, true);  

$source = imagecreatefrompng($fileName);
imagealphablending($source, true);

imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

imagepng($thumb,$newFilename);

我发现使用imagecopyresampled()比使用imagecopyresized()可以得到更好的输出图像质量。


破解了!非常感谢! - BastardPrince
1
最终我使用了imagecopyresampled,这不仅提高了质量,而且imagecopyresized无论如何都无法保留透明度。 - benr
那段代码对我来说并没有起作用,但是将第二行的imagealphablending($thumb, false);更改为imagealphablending($thumb, true);就解决了问题。 - msbg

14

忘掉颜色透明度索引,它在所有渲染产品中都不起作用。相反,使用一个alpha层蒙版:

$image = imagecreatetruecolor($size, $size);

imagealphablending($image, false);
imagesavealpha($image, true);

$trans_layer_overlay = imagecolorallocatealpha($image, 220, 220, 220, 127);
imagefill($image, 0, 0, $trans_layer_overlay);

太棒了!浪费了一个多小时来解决这个问题,你的解决方案是唯一有效的! - Engin Yapici
比以往更完美!你真棒,@user629089。 非常感谢。 - rasputin
3
你为什么使用了 220, 220, 220 - Slava

3

这些函数访问底层的gdlib库,它是一个很好的玩具,但不会产生良好的效果。如果您有选择,最好使用imagemagick。缺点是目前没有好的php绑定,所以您需要通过shell访问它,而在共享主机上通常不允许。


1

你不必将整个背景都填充为透明色,但是 GD 在处理不透明度时并不擅长,除非它是100%(完全不透明)或0%(完全透明)。 - SteJ

1

imagecopyresized 无法正确支持透明度。

imagecopymerge 可以,但它不能调整大小。

解决方案?您可能最终需要手动调整大小。


“imagecopyresampled”是更好的解决方案,特别适用于用户提交的无法在上传前手动调整大小的图像。我觉得这个答案并不是很有帮助。 - SteJ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接