Using GD to change the color of a one color shape on a transparent background while preserving transparency

♀尐吖头ヾ 提交于 2019-12-11 12:31:10

问题


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

?>

回答1:


@ imagecolortransparent($im, $xxxx); //not sure why this works

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.




回答2:


One thing is I couldn't make that working using imagetruecolortopalette either. Not quite sure if you can use the imagefill 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:

$imgname = "whiteim.png";.                                                                                                                                
$im = imagecreatefrompng ($imgname);                                                                                                                    

imagefill($im, 0,0, imagecolorallocate($im, 255,0,0));                                                                                                  

$imgname = "result.png";                                                                                                                                
imagesavealpha($im, True);                                                                                                                              
imagepng($im, $imgname ); // save image as png                                                                                                          
imagedestroy($im);   


来源:https://stackoverflow.com/questions/5276939/using-gd-to-change-the-color-of-a-one-color-shape-on-a-transparent-background-wh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!