Forum Moderators: coopster

Message Too Old, No Replies

How to make a color image B&W via PHP GD support?

         

irock

8:00 pm on Jan 7, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi, I'm able to resample images without scarificing quality; however, I would also like to know how to make a color image B&W using PHP GD support. Is there a way to do this?

Thanks!

jatar_k

8:14 pm on Jan 7, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I have wandered through GD functions and don't see it offhand, have you looked through these?

[php.net...]

there may be something in there that might be useful.

irock

8:23 pm on Jan 7, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I think what I basically need is to output a 256 grayscale image version of the JPG... hmm...

jatar_k

8:24 pm on Jan 7, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



It's funny that there doesn't seem to be a readily apparent solution to this. I would think it would be a common operation.

I was trying to look for a method to change the palette or something similar.

scratch

8:08 am on Jan 28, 2003 (gmt 0)

10+ Year Member



I was researching this last night as i am learning GD. I found two possible solutions, i think both were in the manual. I have yet to try them, but i am sure they work. I was thinking i could have one that does a sepia tone to the image as well with further experimentation. Tell me if you find out one of these works...

Method #1
function ConvertGreyscale($image){
# this file outputs a grey version of specified image

 $total = ImageColorsTotal($image);
 for( $i=0; $i<$total; $i++){
    $old = ImageColorsForIndex($image, $i);
   
    #trying to keep proper saturation when converting
    $commongrey = (int)(($old[red] + $old[green] + $old[blue]) / 3);

    ImageColorSet($image, $i, $commongrey, $commongrey, $commongrey);
 }
}

Method #2
This little function does it for you:

<?
$image_id = imageCreateFromJPEG($image);
for($a=0;$a<imagecolorstotal ($image_id);$a++)
{
$color = ImageColorsForIndex($image_id,$i);
$R=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
$G=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
$B=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
ImageColorSet($image_id, $a, $R, $G, $B);
}
imageJPEG($image_id,"$image");
?>

The .299 , .578 , .114 values are estimations, and add a gamma correction to the colors. For more or less luminace in the result, you can change these values.

Goodluck,
Eric Mulders, Netherlands

rossa at studioware dot net
23-Jan-2002 08:38