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

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