PHP - 图像内更换颜色PHP - 图像内更换颜色(PHP - Replace colour

2019-05-11 21:19发布

我希望有人能帮帮忙,

我做了一个脚本,面具图片...但它是依赖于一种颜色与掩盖(“绿屏”的风格)。 麻烦的是,如果说我遮蔽图像包含的颜色它毁了。

屏蔽之前的图像具有相似的颜色代替我的键控色(0,0,255)的任何一次出现诸如0,0,254我所希望做的是。

我发现根据各地gif文件或256色PNG,因为他们索引的几个解决方案..

所以我的问题是,也将是更有效将其转换为GIF或PNG 256然后通过索引查找和替换的颜色,或通过每个像素查找和替换颜色。

谢谢,

Answer 1:

您需要打开输入文件和扫描每个像素来检查你的chromokey值。

事情是这样的:

// Open input and output image
$src = imagecreatefromJPEG('input.jpg') or die('Problem with source');
$out = ImageCreateTrueColor(imagesx($src),imagesy($src)) or die('Problem In Creating image');

// scan image pixels
for ($x = 0; $x < imagesx($src); $x++) {
    for ($y = 0; $y < imagesy($src); $y++) {
        $src_pix = imagecolorat($src,$x,$y);
        $src_pix_array = rgb_to_array($src_pix);

            // check for chromakey color
            if ($src_pix_array[0] == 0 && $src_pix_array[1] == 0 && $src_pix_array[2] == 255) {
                $src_pix_array[2] = 254;
            }


        imagesetpixel($out, $x, $y, imagecolorallocate($out, $src_pix_array[0], $src_pix_array[1], $src_pix_array[2]));
    }
}


// write $out to disc

imagejpeg($out, 'output.jpg',100) or die('Problem saving output image');
imagedestroy($out);

// split rgb to components
function rgb_to_array($rgb) {
    $a[0] = ($rgb >> 16) & 0xFF;
    $a[1] = ($rgb >> 8) & 0xFF;
    $a[2] = $rgb & 0xFF;

    return $a;
}


Answer 2:

下面是首先将256个托盘替换颜色的解决方案:

//Open Image
$Image = imagecreatefromJPEG('input.jpg') or die('Problem with source');

//set the image to 256 colours
imagetruecolortopalette($Image,0,256);

//Find the Chroma colour
$RemChroma = imagecolorexact( $Image,  0,0,255 );

//Replace Chroma Colour
imagecolorset($Image,$RemChroma,0,0,254);

//Use function to convert back to true colour
imagepalettetotruecolor($Image);




function imagepalettetotruecolor(&$img)
    {
        if (!imageistruecolor($img))
        {
            $w = imagesx($img);
            $h = imagesy($img);
            $img1 = imagecreatetruecolor($w,$h);
            imagecopy($img1,$img,0,0,0,0,$w,$h);
            $img = $img1;
        }
    }

我个人更喜欢radio4fans的解决方案,因为它是无损的,但如果速度是你的目标,这是卓越的。



文章来源: PHP - Replace colour within image