在图像中用透明替换多个颜色

问题描述 投票:1回答:2

我有一个雨雷​​达图像,背景是灰色和白色的大部分。我需要删除背景(灰色/白色)并使其透明。但它不起作用。我已经试过了

   // replace white
   $rgb = imagecolorexact($im, 255, 255, 255);
   imagecolortransparent($im, $rgb);
   // replace grey
   $rgb = imagecolorexact($im, 189, 189, 189);
   imagecolortransparent($im, $rgb);

但这不起作用。它只有一部分透明(白色或灰色)。我无法同时删除这两种颜色。

我真的不知道图像是如何工作的......所以,如果你知道如何实现我想要的东西,请告诉我。

谢谢

enter image description here

php image gd imagick
2个回答
0
投票

首先,将所有灰色像素设为白色。然后使所有白色像素透明。而已。再读一遍:-)

请参阅PHP GD documentation以查看实际参数和详细信息。

// Load up the original image
$src=imagecreatefrompng('weather.png');

// Ensure image is palettised
if(imageistruecolor($src)){
   imagetruecolortopalette($src);
}

// Find nearest colours to white and grey 189
$whiteindex=imagecolorclosest($src,255,255,255);
$greyindex =imagecolorclosest($src,189,189,189);

// Make all greys white and all nearly whites white, and both transparent
imagecolorset($src,$greyindex,255,255,255,127);
imagecolorset($src,$whiteindex,255,255,255,127);

// Write result 
imagepng($src,"result.png");

请注意,您开始使用的代码和上面的代码使用的是随大多数PHP解释器一起安装的GD库。相反,您可以使用IMagick库(这是ImageMagick的PHP绑定),它更加全面。你的代码会变成这样的:

// Move to a format which supports transparency
$imagick->setimageformat('png');

// Set $color to white first
$imagick->transparentPaintImage($color, $alpha, 10 * \Imagick::getQuantum(),false);

// Set $color to grey first
$imagick->transparentPaintImage($color, $alpha, 10 * \Imagick::getQuantum(),false);

0
投票

在Imagemagick中,您可以转换为HCL颜色空间,并选择C(色度)饱和度通道和阈值为0.这将所有灰色/黑/白像素变为黑色,所有颜色像素变为白色。然后将结果放入原始图像的Alpha通道。这假定原始图像是展平图像并且没有其他图层。如果没有,则将图像展平

convert radar.png \( +clone -colorspace HCL -channel 1 -separate -threshold 0 \) -alpha off -compose copy_opacity -composite result.png

注意通道的编号从0(红色或青色),1(绿色或品红色)和2(蓝色或黄色)开始。您可以使用数字或名称。 Imagemagick不会通过颜色空间通道名称跟踪其他颜色空间的颜色。所以这里使用1或绿色。

enter image description here

生成的图像具有透明度,但由于白色背景颜色,在上面显示为白色。

© www.soinside.com 2019 - 2024. All rights reserved.