且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP - 替换图像中的颜色

更新时间:2023-02-19 15:06:26

输入文件并扫描每个像素以检查您的chromokey值。

You need to open the input file and scan each pixel to check for your chromokey value.

像这样:

// 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;
}