Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将图像中的多种颜色替换为透明_Php_Image_Gd_Imagick - Fatal编程技术网

Php 将图像中的多种颜色替换为透明

Php 将图像中的多种颜色替换为透明,php,image,gd,imagick,Php,Image,Gd,Imagick,我这里有一张雨天雷达图像,背景是灰色和白色的部分。我需要删除背景(灰色/白色)并使其透明。但它不起作用。我已经试过了 // replace white $rgb = imagecolorexact($im, 255, 255, 255); imagecolortransparent($im, $rgb); // replace grey $rgb = imagecolorexact($im, 189, 189, 189); imagecolortranspar

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

   // replace white
   $rgb = imagecolorexact($im, 255, 255, 255);
   imagecolortransparent($im, $rgb);
   // replace grey
   $rgb = imagecolorexact($im, 189, 189, 189);
   imagecolortransparent($im, $rgb);
但这是行不通的。它只有一部分是透明的(白色的或灰色的)。我不能同时删除这两种颜色

我真的不知道图像是怎么工作的。。所以,如果你知道实现我想要的方法,请告诉我

谢谢


首先,将所有灰色像素置为白色。然后使所有白色像素透明。就这样。再读一遍:-)

请参阅以检查实际参数和详细信息

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

在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或绿色


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

你可能有分层图像文件吗?如果是这样,你需要先将图像展平。不知道分层图像是什么?你能查一下吗?请提供原始图像进行测试。打开原始图像的链接“但这不起作用”-考虑到实际作用,一点也不奇怪。正如手册所说,“透明颜色是图像的属性,透明度不是颜色的属性。”您可以先将所有灰色部分“重新着色”为白色,然后指定白色作为透明颜色,这样就可以了。需要设置透明度
imagecolortransparent($src,$whiteindex)