Convert an image to grayscale using PHP

convert an image to grayscale image in 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.


Using imagefilter() methods,  such as-IMG_FILTER_GRAYSCALE, IMG_FILTER_COLORIZE  etc.

For example, let’s take below image-

Convert an image to grayscale image in PHP


Let’s jump into the scripting part,


//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');
  //generates error message if process is unsuccessfull
    echo 'Conversion failed.';
//clearing the memory buffer


Grayscale conversion successful
grayscale php



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-

$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');


grayscale conversion PHP



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

Your email address will not be published. Required fields are marked *