note 41579 added to function.imagecopymergegray

From: Date: Thu, 15 Apr 2004 11:18:56 +0000
Subject: note 41579 added to function.imagecopymergegray
Groups: php.notes 
Request: Send a blank email to php-notes+get-68159@lists.php.net to get a copy of this message
In addition to code_couturier too: his code will produce blue pictures, because the value he uses to set the pixel color (the code is incomplete: I first thought it should be $gray) is between 0 and 255, which corresponds to blue levels. To convert the picture to grayscale, use the following code: <?php // replace with your files $originalFileName = "colorPicture.jpg"; $destinationFileName = "bwPicture.jpg"; // create a copy of the original image // works with jpg images // fell free to adapt to other formats ;) $fullPath = explode(".",$originalFileName); $lastIndex = sizeof($fullPath) - 1; $extension = $fullPath[$lastIndex]; if (preg_match("/jpg|jpeg|JPG|JPEG/", $extension)){ $sourceImage = imagecreatefromjpeg($originalFileName); } // get image dimensions $img_width = imageSX($sourceImage); $img_height = imageSY($sourceImage); // convert to grayscale // note: this will NOT affect your original image, unless // originalFileName and destinationFileName are the same for ($y = 0; $y <$img_height; $y++) { for ($x = 0; $x <$img_width; $x++) { $rgb = imagecolorat($sourceImage, $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 // OR operation to compute gray value $grayColor = $grayR | $grayG | $grayB; // set the pixel color imagesetpixel ($sourceImage, $x, $y, $grayColor); imagecolorallocate ($sourceImage, $gray, $gray, $gray); } } // copy pixel values to new file buffer $destinationImage = ImageCreateTrueColor($img_width, $img_height); imagecopy($destinationImage, $sourceImage, 0, 0, 0, 0, $img_width, $img_height); // create file on disk imagejpeg($destinationImage, $destinationFileName); // destroy temp image buffers imagedestroy($destinationImage); imagedestroy($sourceImage); ?> Copy-paste, replace the file names on the top and there you go (picture files must be in same folder as this script. If not, you will have to do your own file management). ---- Manual Page -- http://www.php.net/manual/en/function.imagecopymergegray.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+41579 Delete -- http://master.php.net/manage/user-notes.php?action=delete+41579&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+41579&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#68159) next »