tags:

views:

34

answers:

1

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

+2  A: 

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);
Dennis Haarbrink
It would be extremally time consuming for large images. Thanks for reply but I was rather considering removing all blues and reds from image. But don't know how to do it.
mickula
@mickula: It's impossible for it to get any more efficient than this (perhaps by some constant factor - but not by any asymptotically significant amount). Think about it - each pixel has to be iterated over at least once to either keep the color or change it, unless you're using some image format we aren't aware of that offers additional information.
Cam
` $average = new Imagick( "duzykevarska.png" );header( "Content-Type: image/png" );$clut = new Imagick();$clut->newImage(1, 1, new ImagickPixel("rgb(0,93,0)"));$average->opaquePaintImage(new ImagickPixel("rgb(0,93,0)"), "white", 255, true);echo $average; `
mickula
@mickula: I can't test the code you've posted since I don't have Imagick. Is that the answer to your question? (If so, you should post it as answer and mark it as such) Or is it working, but not performing?
Dennis Haarbrink