我试图使一个图像透明使用GD库从PHP,但运行以下代码,只有一部分将是透明的


I'm trying to make a image transparent using GD library from PHP but running following code, only a portion will be transparent

我正在尝试使用PHP的GD库使图像透明,但运行以下代码,只有一部分将是透明的。

$image = imagecreatefrompng("$second");  
imagealphablending($image, false);
$col_transparent = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $col_transparent);  // set the transparent colour as the background.
imagecolortransparent ($image, $col_transparent); // actually make it transparent
imagesavealpha($image, TRUE);
header( 'Content-Type: image/png' );
imagepng($image);

这里有原始图像:https://postimg.org/image/y68nw57z1/
下面是生成的图像:https://postimg.org/image/o4n3t6ic7/

可以看到,结果图像中存在部分保持白色。
我该如何解决这个问题?

你是洪水填充取代白色像素的图像,但这将不工作的像素完全由非白色像素包围(如在任何油漆程序)。相反,你可以修改白色的定义,使其透明:

$image = imagecreatefrompng($second);
imagetruecolortopalette($image, false, 255);
$index = imagecolorclosest($image, 255, 255, 255); // find index of white.
imagecolorset($image, $index, 0, 0, 0, 127); // replace white with transparent black.
header('Content-Type: image/png');
imagepng($image);