使用 PHP GD 为 PNG 着色

我想使用 PHP GD 为一些 PNG 着色。出于测试目的,我对红色 (255,0,0) 进行了硬编码,稍后将替换为动态变量。

例如我有这两个图像:

图 1: 6Bt.png

图 2: 6Bd.png

使用我的代码,只有图像 2 可以正常工作。 6BC.png

然而,狗图像有某种灰色框,不知道这是从哪里来的。 6BA.png

这是我正在使用的代码:


<?php


$im = imagecreatefrompng('dog.png');


imagealphablending($im, false);

imagesavealpha($im, true);


$w = imagesx($im);

$h = imagesy($im);


for ($x = 0; $x < $w; $x++) {

    for ($y = 0; $y < $h; $y++) {

        $color = imagecolorsforindex($im, imagecolorat($im, $x, $y));


        $r = ($color['red'] * 255) / 255;

        $g = ($color['green'] * 0) / 255;

        $b = ($color['blue'] * 0) / 255;


        imagesetpixel($im, $x, $y, imagecolorallocatealpha($im, $r, $g, $b, $color['alpha']));

    }

}


imagepng($im, 'result.png');

imagedestroy($im);

为什么它适用于图像 2 而不适用于图像 1?我只能想到图像 1 上的某种 alpha 蒙版。


希望有人可以帮助我


手掌心
浏览 159回答 3
3回答

慕斯709654

我已经使用我的代码让它工作了。我所要做的就是添加imagepalettetotruecolor($im);
打开App,查看更多内容
随时随地看视频慕课网APP