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

replace multiple Colors with transparent in an image

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

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

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

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

谢谢

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

参考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");

请注意,您开始使用的代码以及上面的代码使用的是 GD 库,大多数 PHP 解释器都已预装该库。相反,您可以使用更全面的 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);

在 Imagemagick 中,您可以转换为 HCL 色彩空间和 select 类似 C(色度)饱和度的通道和 0 的阈值。这会将所有 grays/black/white 像素变为黑色,将所有颜色像素变为白色。然后将结果放入原图的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 或绿色。

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