【问题标题】:How to make a color transparent in gd lib after merging images?合并图像后如何在gd lib中使颜色透明?
【发布时间】:2020-11-11 05:51:09
【问题描述】:

我正在使用 gd lib 合并多个图像,但我遇到了透明度问题。首先,我合并了几个图像,每个图像都有一个透明的背景(工作正常)。然后我想在上面放另一张图片,它由三部分组成:我要保留的一部分,下面的图像应该显示的透明部分和应该变成透明的颜色(例如绿色#00ff00)的一部分以及合并后。图像是像素图像,所以我只希望#0f0 变得透明,没有其他颜色。

Here is an image of the result of the code. 第一张图片显示了合并后的图像(“圆”和“云”)。 第二张图片显示了放在合并图像顶部的“帽子”。 第三张图片显示了我想要达到的结果。 第四张图是我实际得到的。

无论我做什么,我似乎都找不到解决方案。非常感谢您的帮助!

    header("Content-type: image/png");
    $img = imagecreatetruecolor(200, 200);
    
    //make an image with transparent background
    $transparency = imagecolorallocatealpha($img, 0, 0, 0, 127);
    imagefill($img, 0, 0, $transparency);
    imagesavealpha($img, true);

    $circle = imagecreatefrompng("testcircle.png"); //black circle
    $cloud = imagecreatefrompng("testcloud.png"); //brown cloud
    $hat = imagecreatefrompng("testhat.png"); //blue hat with green area

    imagecopy($img, $circle, 0, 0, 0, 0, 200, 200);
    imagealphablending($img,true);
    imagecopy($img, $cloud, 0, 0, 0, 0, 200, 200);
    imagealphablending($img,true);

    $green = imagecolorallocate($hat, 0, 255, 0);
    imagecolortransparent($hat, $green);
    imagecopy($img, $hat, 0, 0, 0, 0, 200, 200);
    imagealphablending($img,true);

    /* //With this the green area just keeps being green as in the second picture
    $green = imagecolorallocate($img, 0, 255, 0);
    imagecolortransparent($img, $green);
    imagecopy($img, $hat, 0, 0, 0, 0, 200, 200);
    imagealphablending($img,true);
    */

    imagepng($img);
    imagedestroy($img);

【问题讨论】:

    标签: php transparency gd gdlib


    【解决方案1】:

    找了很久,终于找到了解决问题的办法。如果以后有人和我有同样的问题,我希望它会有所帮助。

    $green = imagecolorallocate($img, 0, 255, 0);
    imagecopy($img, $hat, 0, 0, 0, 0, 200, 200);
    imagecolortransparent($img, $green);
    imagefill($img,0,0,imagecolorallocatealpha($img, 0, 0, 0, 127)); //this line does the trick
    

    首先,我将绿色定义为一种颜色。然后我将“帽子”复制到图片上并使颜色透明。然后是填充图片的技巧,它使绿色区域再次透明。 (I found the solution in a german forum)。

    我注意到这段代码只使第一个绿色区域透明。如果有两个单独的区域(甚至更多),(至少)一个会保持绿色。因此,虽然这是一个适合我的解决方案,但可能会有更好的解决方案。

    【讨论】:

      猜你喜欢
      • 2011-04-25
      • 2012-01-21
      • 2012-04-19
      • 1970-01-01
      • 2012-03-06
      • 2010-12-02
      • 2019-02-15
      • 2010-11-06
      • 2011-06-21
      相关资源
      最近更新 更多