Bubble.ro - because there is always something new to learn about

How to check if an image is grayscale in PHP


Category: Programming/PHP

Images, even if they are big or small are usually full of colour. However, in certain situations you may want to check if an image is indeed grayscale or not. You can do this using PHP and its image manipulation functions.

How to extract RGB values from an image using PHP

RGB stands for Red, Green, and Blue - together forming a colorimetric system (color model) frequently used. Any color image can be represented in this system - the three channels can be used to manipulate the image in various ways.

However, in PHP, user doesn't have direct access to pixel values directly from memory and, most important, doesn't have access even to each channel separately by default.

In order to extract the RGB values, first we need each pixel value - for this, you can simply use the ImageColorAt() function, function bundled into the GD library.

Of course, in order to know the position of each pixel, one important thing to know is the image width and height. These can be extracted either using getimagesize() or, when you create an image object imagesx() and imagesy().
$source_file = "test_image.jpg";

$im = ImageCreateFromJpeg ($source_file);

$imgw = imagesx($im);
$imgh = imagesy($im);
Of course, you can use different functions to load GIF or PNG files, but no other changes are needed whatsoever in any of the processing part.
$r = array();
$g = array();
$b = array();

for ($i=0; $i<$imgw; $i++)
        for ($j=0; $j<$imgh; $j++)
                // get the rgb value for current pixel
                $rgb = ImageColorAt($im, $i, $j);
                // extract each value for r, g, b
                $r[$i][$j] = ($rgb >> 16) & 0xFF;
                $g[$i][$j] = ($rgb >> 8) & 0xFF;
                $b[$i][$j] = $rgb & 0xFF;
At the end of this script, the variables $r, $g, $b will have the apropriate values for each pixel.

Grayscale or true color?

Now, as an application for these values, we could check if an image is grayscale or true color.

Grayscale images have the property that every pixel only contains a gray value - which mathematically can be defined as pixels which have the $r, $g and $b value equal.

The script that is listed counts the number of gray pixels and compares it with the number of total pixels (width * height).
$source_file = "test_image.jpg";

$im = ImageCreateFromJpeg($source_file);

$imgw = imagesx($im);
$imgh = imagesy($im);

$r = array();
$g = array();
$b = array();

$c = 0;

for ($i=0; $i<$imgw; $i++)
        for ($j=0; $j<$imgh; $j++)
                // get the rgb value for current pixel
                $rgb = ImageColorAt($im, $i, $j);
                // extract each value for r, g, b
                $r[$i][$j] = ($rgb >> 16) & 0xFF;
                $g[$i][$j] = ($rgb >> 8) & 0xFF;
                $b[$i][$j] = $rgb & 0xFF;
                // count gray pixels (r=g=b)
                if ($r[$i][$j] == $g[$i][$j] && $r[$i][$j] == $b[$i][$j])

if ($c == ($imgw*$imgh))
        echo "The image is grayscale.";
        echo "The image is NOT grayscale.";

Please note that image manipulation functions are particularly VERY slow in PHP. This example alone might not be the worst example, but avoid allowing insecure access to scripts that operate with such functions, or try to use various methods to limit access, since it use plenty of server resources.

Related links:

- source files (1K)
- PHP Image functions

Posted by: Indy on October 28, 2006 at 08:15.

» Comments

Saving Resources
You could save resources by breaking out of the loop when the average value doesn't equal, say, the red value. If it does step all the way through it's grayscale.

Posted by Steven Jackson on May 8, 2007 at 04:40 PM.

image checking is not working for the tiff formate
Great Work with PNG, JPG and gif , i want to check for the tiff format image.

But its not working for tiff.

Please help in this regard, it will be highly appreciated

Posted by jamal on July 17, 2011 at 07:13 AM.

I made a function from the above code
Recently my script based on Imagick stopped working, so I'm using this now to check if an image is greyscale.

* Returns whether image is greyscale or not.
* @param string$image_path
* @return boolean
function greyScaleImage($image_path) {
$info = GetImageSize($image_path);
$imgw = $info[0];
$imgh = $info[1];

switch ($info[2]) {
$image = @ImageCreateFromGif($image);
$image = @ImageCreateFromJpeg($image);
$image = @ImageCreateFromPng($image);
return false;

for ($i = 0; $i < $imgw; $i++) {
for ($j = 0; $j < $imgh; $j++) {
// get the rgb value for current pixel
$rgb = ImageColorAt($image, $i, $j);
// extract each value for r, g, b
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
// if gray pixels (r=g=b) check next otherwise it's not greyscale
if ($r != $g || $r != $b) {
return false;
return true;

Posted by Emanuele on January 21, 2016 at 04:07 AM.

Random Article



Bubble.ro RSS Feed

All Categories


Aetolia - The Midnight Age
How to create the histogram of an image using PHP
How to convert an image to grayscale using PHP
How to check if an image is grayscale in PHP
Interchanging 2 variables without the use of a third
Error launching browser window:no XBL binding for browser
Convert the AOL user session collection to a MySQL database
Introduction to Matlab
Creating a customized session handling system in PHP (part II)
Creating a customized session handling system in PHP (part I)
Firefox crashing with Yahoo! Messenger
ADL Search for oDC
Video codecs explained
How to use Auto-Away Message with oDC
Create complete Windows XP disk with SP2 and all updates
Data Execution Prevention error message in Windows XP
Google Mars
Logarithmic scale graphs in Excel
Urban Dictionary (or wtf does l33t mean?)
Learn more about BIOS
Backup your Firefox and Thunderbird settings
Syndicate your Yahoo 360 profile
What is Google PageRank?
'Cannot Open the File: Mk:@MSITStore' Error Message
Get your Gmail with Mozilla Thunderbird
E-Books links
Change the size of your Explorer thumbnails
Remove previews from Windows Explorer
How can I turn off system beeps?
How do I disable Internet Explorer?
What are proxies or how do I protect my anonymity?
How to set aliases triggers or macros in MushClient
What is RSS?
Palm Zire 31 fast review
oDC Installation and Basic Configuration
How I built a 2x80W amplifier (using power modules)
Leech/HotLink Protection
How to block referrer detection?
How to find out your IP address
Getting started with Mushclient
What is spyware and how do I protect my PC from it?
Stumble Upon - random surfing around the web
Automatic file backup for Windows users
How can I read foreign language sites?
Protect your web surfing privacy!
What is BitTorrent?
No more ads! Adblock for Firefox
Why use Firefox instead of Internet Explorer?
How do I create my own Yahoo ID?
© Copyright 2006-2017 Bubble. All rights reserved. Sitemap - Contact