How to isolate only one color in an image using PHP?

Is it possible to leave (isolate) only one color in the image? I'm currently interested in green: 005d00

+3
source share
2 answers

Well, you can do this using ImageMagick via the command line:

convert original.png -matte ( +clone -fuzz 1 -transparent #005d00 ) -compose DstOut -composite isolated.png

The -fuzz command can accept a percentage deviation from the color, if it is specific, reset the fuzz.

Brackets () must be executed in bash shell \ (\), etc.

+1
source

gd imagecolorat().
, , , set , .

:

function colorEquals($rgb_color, $hex_color)
{
    $r = ($rgb_color >> 16) & 0xFF;
    $g = ($rgb_color >> 8) & 0xFF;
    $b = $rgb_color & 0xFF;


    list($hr, $hg, $hb) = sscanf($hex_color, '%2s%2s%2s');
    $hr = hexdec($hr);
    $hg = hexdec($hg);
    $hb = hexdec($hb);

    return $r == $hr && $g == $hg && $b == $hb;
}

$width = 300;
$height = 300;

// create 300x300 image
$img = imagecreatetruecolor($width, $height);
// fill grey
$color = imagecolorallocate($img, 127, 127, 127);
imagefill($img, 0, 0, $color);

// set a square of pixels to 005d00
$your_color = imagecolorallocate($img, 0, 93, 0);
imagefilledrectangle($img, 10, 10, 100, 100, $your_color);

$white = imagecolorallocate($img, 255, 255, 255);

for($x = 0; $x < $width; ++$x)
{
    for($y = 0; $y < $height; ++$y)
    {
        $color = imagecolorat($img, $x, $y);
        if(!colorEquals($color, '005d00'))
        {
            // set it to white
            imagesetpixel($img, $x, $y, $white);
        }
    }
}

// output
header('Content-type: image/png');
imagepng($img);
+2

Source: https://habr.com/ru/post/1765403/


All Articles