How to convert an image to Grayscale in PHP

In this article, I am going to tell you how to convert a normal colored or any RGB image to a grayscale image in PHP.

Before I go through, let me tell you what is actually a Grayscale image is.

A grayscale image is a type of image that only contains various levels of gray in that image. These types of images can be expressed as RGB.

See the two images below:

RGB and grayscale image

On the left-hand side, it is a, as usual, colored image which is called RGB image. On the right-hand side, we can see the grayscale image converted from the same image.

Many of us call the grayscale image “black and white”. But actually this is not a black and white image. Black and white image is different than the grayscale image. Black and white can only be formed in black and white colors.

So grayscale is the proper type name for these images that you can see on the right side of the above picture as an example.

PHP code to convert an RGB image to Grayscale image

Now, let’s see the necessary PHP code that required to convert a colored image to a grayscale image. We are going to use PHP in-built functions to perform our tasks and will not use any type of library.

Below is our PHP code that can do that:

<?php
$imgcreate = imagecreatefrompng('forest.png');

if($imgcreate && imagefilter($imgcreate, IMG_FILTER_GRAYSCALE))
{
    echo 'Grayscale image generated.';

    imagepng($imgcreate, 'forest_gray.png');
}
else
{
    echo 'Grayscale conversion of image failed.';
}

imagedestroy($imgcreate);
?>

In the above code, we have used the imagecreatefrompng to create our image. To convert our image into grayscale, we have used the imagefilter() PHP function to filter our image. To get the grayscale image, we have passed IMG_FILTER_GRAYSCALE as the filter type.

Here, the important role to get a grayscale image is played by the imagefilter() function and the IMG_FILTER_GRAYSCALE parameter as the filter type.

The IMG_FILTER_GRAYSCALE has the ability to turn our original image into a grayscale image by changing the red, green and blue components to their weighted sum of the image using some mathematics task.

Also, read:

As the final output of our code, we can see a new image created having the file name “forest_gray.png”. If we open the image, we can see a grayscale image.

If we give the image name as the same “forest.png” than our original image will be removed and it will be replaced with our grayscale image.

 

Leave a Reply

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