在PHP中更改PNG非透明部分的颜色

3

我希望使用PHP将PNG图片中的非透明部分填充为任何颜色或图像。

以下是基础图片:

透明猫

以下是目标图片:

有色猫

我已经使用了以下PHP代码来填充PNG图片中的非透明部分:

$im = imagecreatefrompng(dirname(__FILE__) . '/images/cat_1.png');
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im, 0, 0, $red);
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);

但是它给我以下输出。 cat的错误输出 请帮助我完成任务。
提前致谢。
3个回答

2

这行代码 imagefill($im, 0, 0, $red); 用颜色红色填充了图像,在坐标(0,0)即左上角开始填充。就像在MSPaint中使用油漆桶一样,从左上角开始填充整个区域。例如,您可以使用 imagefill($im, 150, 150, $red); (如果150,150是中心点),来填充图像。


2

保存此基础图像版本:

基础图像

该图像已被保存为索引PNG格式,非常适合颜色替换。在这种情况下,索引0是猫的颜色,索引1是背景(不是理想的选择,但这是GIMP给我的)

在这种情况下:

$img = imagecreatefrompng("cat_1.png");
imagecolorset($img,0, 255,0,0);
imagepng($img); // output red cat

如果您有一张适合进行这种简单编辑的基础图片,那么通常情况下图像编辑会变得更加容易 :)


你知道我怎么用图案图片代替红色吗? - user3394113
虽然不像使用两种颜色那样容易,但您可以在所需的图案中使用多于两种颜色,并动态更改这些颜色。 - Niet the Dark Absol

0

使用此函数,它将返回一个base64图像 <img src="output">

public static function colorImage($url, $hex = null, $r = null, $g = null, $b = null)
{

    if ($hex != null) {
        $hex = str_replace("#", "", $hex);
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));
    }
    $im = imagecreatefrompng($url);
    imageAlphaBlending($im, true);
    imageSaveAlpha($im, true);

    if (imageistruecolor($im)) {
        $sx = imagesx($im);
        $sy = imagesy($im);
        for ($x = 0; $x < $sx; $x++) {
            for ($y = 0; $y < $sy; $y++) {
                $c = imagecolorat($im, $x, $y);
                $a = $c & 0xFF000000;
                $newColor = $a | $r << 16 | $g << 8 | $b;
                imagesetpixel($im, $x, $y, $newColor);
            }
        }
    }
    ob_start();

    imagepng($im);
    imagedestroy($im);
    $image_data = ob_get_contents();

    ob_end_clean();

    $image_data_base64 = "data:image/png;base64," . base64_encode($image_data);

    return $image_data_base64;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接