Convert a Colorful Image to Grayscale Image Using PHP

In this tutorial, we will introduce the way to convert a colorful image to a grayscale image using php.

1. Open a png image

<?php
$im = imagecreatefrompng('colorful.png');
?>

2. Convert it to grayscale image

We will use php imagefilter() function to convert.

<?php
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);
?>