Convert an image to grayscale using PHP

In this article, we will discuss different methods to convert an image into a grayscale image in PHP. We will discuss both the predefined method as well as the user-defined methods.
Convert an image to grayscale in PHP using predefined methods
PHP introduced predefined effects for image manipulation.
Example:-
Using imagefilter() methods, such as-IMG_FILTER_GRAYSCALE, IMG_FILTER_COLORIZE etc.
For example, let’s take below image-

before
Let’s jump into the scripting part,
<?php //Opening the png file $im = imagecreatefrompng('colorful.png'); //applying grascale filter if($im && imagefilter($im, IMG_FILTER_GRAYSCALE)) { echo 'Grayscale conversion successful'; //Saving and replacing the original png file with the grayscale png imagepng($im, 'colorful.png'); } else { //generates error message if process is unsuccessfull echo 'Conversion failed.'; } //clearing the memory buffer imagedestroy($im); ?>
Output:-
Grayscale conversion successful

after
Note:-
In this method, the original image is replaced by the grayscale image. So before running the script, make a backup.
How to convert to grayscale using the user-defined method
There are many ways to add a grayscale effect, I am discussing one of them as follows-
<?php $file = "colorful.jpg"; $img = ImageCreateFromJpeg($file); $imw = imagesx($img); $imh = imagesy($img); for ($i=0; $i<$imw; $i++) { for ($j=0; $j<$imh; $j++) { //collect the rgb value from the current pixel of image $rgb = ImageColorAt($img, $i, $j); // extract r,g,b value separately $r = ($rgb >> 16) & 0xFF; $g = ($rgb >> 8) & 0xFF; $b = $rgb & 0xFF; // get value from rgb scale $gr = round(($r + $g + $b) / 3); // gray values have r=g=b=gr $val = imagecolorallocate($img, $gr, $gr, $gr); // set the gray value imagesetpixel ($img, $i, $j, $val); } } header('Content-type: image/jpeg'); imagejpeg($img); ?>
Output:-

After
Note:-
There are different methods that are there for opening and displaying different image types like- for .jpeg files the opening method is ImageCreateFromJpeg().
This is how we can add a grayscale effect to an image using PHP.
Also read,
Leave a Reply