views:

40

answers:

2

Hi all,

I'm looking for a way of converting an image so that all non-transparent pixels (those that have alpha != 1) into black and transparent pixels untouched (or converted to white). The closest I got was with the below imagemagick command:

convert <img> -colorspace Gray <out>

However this still gives me some gray colors instead of a complete black. I have tried all colorspace options and none does the job.

Any idea how I could achieve this with imagemagick or with similar tools (or with a PHP library if it exists)

Thanks

+1  A: 

I'm not sure whether it'll help you (i.e. whether the methods presented will leave the transparent pixels alone) but check out the answers to this question: PHP/ImageMagic Get the “shadow” of an image

Pekka
+1  A: 

Well, you could do it with GD and a pair of loops:

$img = imagecreatefromstring(file_get_contents($imgFile));
$width = imagesx($img);
$hieght = imagesy($img);

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

for ($x = 0; $x < $width; $x++) {
    for ($y = 0; $y < $width; $y++) {
        $color = imagecolorat($img, $x, $y);
        $color = imagecolorforindex($color);
        if ($color['alpha'] == 1) {
            imagesetpixel($img, $x, $y, $black);
        } else {
            imagesetpixel($img, $x, $y, $white);
        }
    }
}

Or, you could replace colors (this may or may not work):

$img = imagecreatefromstring(file_get_contents($imgFile));
$maxcolors = imagecolorstotal($img);
for ($i = 1; $i <= $maxcolors; $i++) {
    $color = imagecolorforindex($i);
    if ($color['alpha'] == 1) {
        imagecolorset($img, $i, 0, 0, 0);
    } else {
        imagecolorset($img, $i, 255, 255, 255);
    }
}
ircmaxell