Drupal – Desaturate (black/white) an image using GD library

If u r using PHP GD library for image customization thn here’s a sample code for php developer to desaturate (black/white) an image using GD library.

if (!function_exists('webshopmodule_image_desaturate')) {
 function webshopmodule_image_desaturate($source, $destination) {
 $info = image_get_info($source);
 if (!$info) {
 return FALSE;
 }
 $width  = $info['width'];
 $height = $info['height'];

 $im = image_gd_open($source, $info['extension']);
 //$res = imageCreateTrueColor($width, $height);
 $res = @imagecreatetruecolor($width, $height);

 for ($y = 0; $y < $height; ++$y)
 for ($x = 0; $x < $width; ++$x) {
 $rgb = imagecolorat($im, $x, $y);
 $red   = ($rgb >> 16) & 0xFF;
 $green = ($rgb >> 8)  & 0xFF;
 $blue  = $rgb & 0xFF;

 $gray = round(.299*$red + .587*$green + .114*$blue);

 // shift gray level to the left
 $grayR = $gray << 16;   // R: red
 $grayG = $gray << 8;    // G: green
 $grayB = $gray;         // B: blue
 $grayColor = $grayR | $grayG | $grayB;

 // set the pixel color
 imagesetpixel($res, $x, $y, $grayColor);
 imagecolorallocate($res, $gray, $gray, $gray);
 }

 $result = image_gd_close($res, $destination, $info['extension']);

 imageDestroy($res);
 imageDestroy($im);

 return $result;
 }
}


// Here 'webshopmodule' is my module name

3 thoughts on “Drupal – Desaturate (black/white) an image using GD library

  1. As GD does not natively offer desaturation capabilities, this method is satisfactory for its results. One would cringe at running this code under most interpreted languages, but as PHP is ‘compiled’ into bytecode beforehand, it tends to be much quicker.

Leave a comment