PHP - Замените цвет в рамках изображения

Моя любимая часть: использование их для упрощения модульных тестов записи. Также цепочки IEnumerable убедили меня записать более быстрые интерфейсы в своем коде.

Недостатки: Лямбды и дополнительные методы являются моими молотками, и всеми проблемами являются гвозди.

В целом: вдохнувший новую жизнь программирование в C# для меня.

6
задан Mark 10 October 2009 в 17:26
поделиться

2 ответа

Вам нужно открыть входной файл и просканировать каждый пиксель, чтобы проверить значение хромоключа.

Примерно так:

// 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;
}
9
ответ дан 9 December 2019 в 22:36
поделиться

Here is the replace colour solution that first converts to 256 pallet:

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

I personally prefer radio4fans solution as it is lossless, but if speed is your goal this is superior.

2
ответ дан 9 December 2019 в 22:36
поделиться
Другие вопросы по тегам:

Похожие вопросы: