开发者

How to isolate only one colour on image with PHP?

Is it possible to leave (isolate) only one colour in image? Currently I'm interested in gr开发者_如何学运维een:005d00


You could use gd's imagecolorat() function.
Just iterate over every pixel, check if it is the color you want, otherwise set it to black or white or whatever you want to do with it.

Here's a working example:

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);


Well you can do it using ImageMagick via the command line:

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

The -fuzz command can take a percentage variance from the colour, if it's specific, drop the fuzz.

The () brackets need escaping in bash shell \( \), etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜