开发者

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

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开发者_运维问答);

?>


@ 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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜