Wednesday, February 23, 2011

Convert an image to gray scale

PHP provides a very strong support for image manipulation. You can convert any image into its grey scale equivalent easily. The only thing you need to know apart from the given code is how to generate a black and white version of a particular color.

What I mean to say is, take any color for example. May be red. We have to know the rgb equivalent of it. In our case the rgb equivalent of red is rgb(255,0,0). Now the grey scale equivalent of that is as follows:

Grey Scale:
Red = (255 + 0 + 0) /3
Green = (255 + 0 + 0) /3
Blue = (255 + 0 + 0) /3
that is
  rgb(85,85,85)= grey scale of red

Anyways, here's the code ;)



<?php
$source_file = "test_image.jpg";
$im = ImageCreateFromJpeg($source_file);
$imgw = imagesx($im);
$imgh = imagesy($im);
for ($i=0; $i<$imgw; $i++)
{
 for ($j=0; $j<$imgh; $j++)
 {
  $rgb = ImageColorAt($im, $i, $j);
  $rr = ($rgb >> 16) & 0xFF;
  $gg = ($rgb >> 8) & 0xFF;
  $bb = $rgb & 0xFF;
  $g = round(($rr + $gg + $bb) / 3);
  $val = imagecolorallocate($im, $g, $g, $g);
  imagesetpixel ($im, $i, $j, $val);
 }
}
header('Content-type: image/jpeg');
imagejpeg($im);
?>

Cheers!!

1 comment:

  1. hmm, i have tested it with

    1. $val = imagecolorallocate($im, $g, $g, $g);
    2. $val = imagecolorallocate($im, $gg, $gg, $gg);
    3. $val = imagecolorallocate($im, $rr, $rr, $rr);
    4. $val = imagecolorallocate($im, $bb, $bb, $bb);

    and always get the same result !? :-)

    ReplyDelete