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

时间:2014-10-09 13:02:45

标签: php

我想用php填充任何颜色或图像的png非透明部分。

以下是基本图像

transparent cat

以下是目标图像

colored cat

我使用了以下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);

但是它给了我以下输出。

wrong output of cat

请帮我完成我的任务。

提前致谢。

3 个答案:

答案 0 :(得分:2)

保存此版本的基本影像:

Base image

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

在这种情况下:

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

如果您的基本图像能够以这种方式轻松编辑,通常可以更轻松地进行图像编辑;)

答案 1 :(得分:1)

这一行imagefill($im, 0, 0, $red);用红色填充图像,坐标为(0,0),为topleft。所以它开始在左上方填充并填充所有内容,就像你在MSPaint中使用paintbucket一样。例如,您可以使用imagefill($im, 150, 150, $red);(如果150,150是中心)。

答案 2 :(得分: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;
}