Converting Image to Grayscale with PHP

As everybody knows, converting images offline into grayscale in GIMP (or probably Photoshop) is just 2 clicks away. But how about converting them on the fly? Anyways, here’s a simple steps to convert an image into grayscale with PHP and GD library.

Getting Started

Let’s begin by choosing your image. For this example, I am using a yummy chicken noodle from Solaria restaurant. 🙂

The main idea is to read every pixel’s RGB value and convert them using YIQ colorspace conversion matrix. We only need the Y value for the result color.

So, here’s the function to get the Y value from an RGB color:

<?php
// Function to get grayscale color from RGB
function grayscale($color) {
$r = ($color >> 16) & 0xFF;
$g = ($color >> 8) & 0xFF;
$b = $color & 0xFF;
$yiq = round($r*0.299 + $g*0.587 + $b*0.114);
return sprintf("0x%02x%02x%02x", $yiq, $yiq, $yiq);
}

$color is in hexadecimal numbers, for example, a magenta color is 0xADD8E6 in hex. We separate its RGB values using binary SHIFT and AND operators, so we have $r = 0xAD, $g = 0xD8, $b = 0xE6.

The grayscale value is calculated by adding about 30% red, 59% green, and 11% blue. Don’t forget to round the result.

As we are working in RGB, so we return the color back in RGB value. So 0xADD8E6 becomes 0xCDCDCD.

Next, change the content type as image:

header("Content-type: image/jpeg");

Get the image resolution and load it into $img // Image file to be converted
$file = “mie-ayam.jpg”;

// Get image width & height
list($width, $height) = getimagesize($file);

// Load source image file
$img = imagecreatefromjpeg($file);

Now, replace every pixel into grayscale using the function above:

for($y = 0; $y < $height; $y++) {
for($x = 0; $x < $width; $x++) {
$rgb = imagecolorat($img, $x, $y);
$gray = grayscale($rgb);
imagesetpixel($img, $x, $y, $gray);
}
}

Finally we output the JPG image and clear memory

header("Content-type: image/jpeg");
imagejpeg($img);
imagedestroy($img);

Download the file (573 bytes)

Reference:

Wikipedia
Prosoxi

Write Comments