使用 PHP 实现 PNG 透明度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/313070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PNG Transparency with PHP
提问by BastardPrince
Hey having some trouble trying to maintain transparency on a png when i create a thumbnail from it, anyone any experience with this? any help would be great, here's what i am currently doing:
嘿,当我从中创建缩略图时,试图保持 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);
回答by Tom Haigh
I have had success doing it like this in the past:
我过去曾成功地这样做过:
$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);
I found the output image quality much better using imagecopyresampled()than imagecopyresized()
我发现输出图像质量比使用imagecopyresampled()好得多imagecopyresized()
回答by user629089
Forget the color transparency index, it never works in all rendering products. Instead use an alpha layer mask:
忘记颜色透明度指数,它在所有渲染产品中都不起作用。而是使用 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);
回答by troelskn
Those functions access the underlying gdlib library, which is a fine toy, but not something that makes for nice results. If you have the option, use imagemagickinstead. The downside is that there are currently no good php-bindings, so you need to access it over the shell, which you're usually not allowed on shared hosts.
这些函数访问底层的 gdlib 库,这是一个很好的玩具,但不会产生好的结果。如果可以,请改用imagemagick。缺点是目前没有好的 php 绑定,所以你需要通过 shell 访问它,这通常在共享主机上是不允许的。
回答by Paul Fisher
See dycey's answer to "How do I resize...". Essentially, you need to fill the entire background with transparency before you do any other operations.
请参阅dycey 对“如何调整大小...”的回答。本质上,您需要在执行任何其他操作之前用透明度填充整个背景。
回答by strager
imagecopyresizeddoes not support transparency properly.
imagecopyresized不正确支持透明度。
imagecopymergedoes, but it doesn't resize.
imagecopymerge可以,但不会调整大小。
The solution? You'd probably end up resizing the thing manually.
解决方案?您可能最终会手动调整大小。

