使用 GD 更改透明背景上单色形状的颜色,同时保持透明度
我有一个 png,它是透明背景上的一组白色形状。我正在尝试更改形状的颜色,同时保留透明背景。我一直在尝试下面的代码,它确实改变了颜色,但结果是黑色背景。我认为 imagetruecolortopalette 导致了问题,但如果我删除该行,颜色不会改变。有什么建议吗?
<?php
$imgname = "whiteim.png";
$im = imagecreatefrompng ($imgname);
imagetruecolortopalette($im,false, 255);
$index = imagecolorclosest ( $im, 255,255,255 ); // get White COlor
imagecolorset($im,$index,255,0,0); // SET NEW COLOR
$imgname = "result.png";
imagepng($im, $imgname ); // save image as png
imagedestroy($im);
?>
I have a png that is a set of white shape on a transparent background. I'm trying to change to color of the shapes while preserving the transparent background. I've been experimenting with the code below which does change the color but results in a black background. I think the imagetruecolortopalette is causing the problem but the color doesn't change if I remove that line.Any suggestions?
<?php
$imgname = "whiteim.png";
$im = imagecreatefrompng ($imgname);
imagetruecolortopalette($im,false, 255);
$index = imagecolorclosest ( $im, 255,255,255 ); // get White COlor
imagecolorset($im,$index,255,0,0); // SET NEW COLOR
$imgname = "result.png";
imagepng($im, $imgname ); // save image as png
imagedestroy($im);
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这有效是因为
imagecolortransparent
使给定颜色(放置 $xxxx 的位置)透明,在这种情况下 $xxxx 不包含任何值。因此,透明的是所有不包含颜色值的像素。I think this work because
imagecolortransparent
makes the given color (where you placed $xxxx) transparent, in this case $xxxx contains no value. So what is made transparent are all the pixels that contain no color value.一件事是我也无法使用 imagetruecolortopalette 来实现这一点。不太确定是否可以使用
imagefill
在您的情况下功能(您需要知道从哪里开始填充,如果您有一个白色区域,它就可以工作),但这就是我使用的。另一件事是,您似乎需要调用
imagesavealpha
在将任何 alpha 信息保存到 png 图像之前,否则它会丢失。我很难告诉我为什么它不是默认设置。总而言之,我的方法是:
One thing is I couldn't make that working using
imagetruecolortopalette
either. Not quite sure if you can use theimagefill
function in your case (you need to know where to start the fill and it works if you have one area of white), but this is what I've used.The other thing is that it seems like you need to call
imagesavealpha
before you save any alpha information to a png image, otherwise it's lost. Hard to tell for me why isn't it a default setting.All in all, my approach was: