如何使用GD在png 24 alpha透明图像中将一种颜色替换为另一种颜色

mer*_*cam 1 php gd image-processing

我试过了:

$index = imagecolorresolve ( $im,  0,0,0 ); // get black
imagecolorset($im, $index, 255, 0, 255); // SET NEW COLOR
Run Code Online (Sandbox Code Playgroud)

这似乎适用于png 8,但不适用于24,如果我用8执行,那么由于抗锯齿,它会变得奇怪.

这是我正在使用的完整测试代码.(这只是测试代码,所以要温和).

function LoadPNG($imgname, $color = false)
{        
    $im = @imagecreatefrompng($imgname);
    imagealphablending($im, false); 

    if($color) {
      $index = imagecolorresolve ( $im,  0,0,0 ); // get black
      imagecolorset($im, $index, 255, 0, 255); // SET NEW COLOR
    }

    imageAlphaBlending($im, true);
    imageSaveAlpha($im, true);

    return $im;
}

header('Content-Type: image/png');

$img = LoadPNG("head.png", "red");

imagepng($img);
imagedestroy($img);
Run Code Online (Sandbox Code Playgroud)

Ben*_*ier 7

根据inti的解决方案,我制作了一个有效的脚本:

$imgname = "yourimage.png";
$im = imagecreatefrompng($imgname);
imagealphablending($im, false);
for ($x = imagesx($im); $x--;) {
    for ($y = imagesy($im); $y--;) {
        $rgb = imagecolorat($im, $x, $y);
        $c = imagecolorsforindex($im, $rgb);
        if ($c['red'] < 40 && $c['green'] < 40 && $c['blue'] < 40) { // dark colors
            // here we use the new color, but the original alpha channel
            $colorB = imagecolorallocatealpha($im, 255, 0, 255, $c['alpha']);
            imagesetpixel($im, $x, $y, $colorB);
        }
    }
}
imageAlphaBlending($im, true);
imageSaveAlpha($im, true);
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
Run Code Online (Sandbox Code Playgroud)

我想要一种优化它的方法,因为它很慢