How to convert Hex Colour Codes into RGB Colour Codes using PHP

, ,

I was recently working on a web based piece of software that had some colour settings stored in a database table which were stored as hexadecimal colour code values. I needed a quick way to convert them into RGB (Red, Green, Blue) values so that I could use them in creating an image using PHPs builtin GD so after a quick search on Google found nothing that I was really after I decided to write my own. The difficulty was that colours were inputted by both other developers and a jQuery colour picker which meant that there was a mix of both shorthand and standard hexadecimal colour codes. I get past this little hiccup by simply counting the length of the hex string and running either a bitwise operation or a hexadecimal conversion. Anyway onto the function.

Firstly, we need to define the function.  We will have two variables, one being the actual hexadecimal colour code and the other whether we wish to return as a String or Array.

function hex2RGB($hexStr, $returnAsString = false) {
    $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr);
    $rgbArray = array();

After this we simply grab the variable of the function which should be our Hex colour code and check the length.  If the length is 6 then we are able to use PHPs bitwise operators to quickly convert the colour codes into the RGB values we are after. Using bitwise operators results in lower overhead and therefore leads to a faster output.

    if (strlen($hexStr) == 6) { // Proper Hex convert using bitwise operation
        $colorVal = hexdec($hexStr);
        $rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
        $rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
        $rgbArray['blue'] = 0xFF & $colorVal;
    }

Or if it is a shorthand hex colour code (ie: #FFF) then we can perform manipulation on the string to first extend it and then perform a conversion.

elseif (strlen($hexStr) == 3) { // If shorthand perform string manipulations
        $rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
        $rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
        $rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
    }

or else if our string matches neither of the above then return nothing (false).

else {
        return false; // Invalid hex color code
    }

Now that we have our converted code, we need to return it back to what called for the code with the following in either an array or as a string.

    // Returns the rgb string or the associative array as specified
    return $returnAsString ? implode(",", $rgbArray) : $rgbArray;
}

We can call the above function in two ways

hex2RGB(“#FF0”) would output array( red =>255, green => 255, blue => 0)
or
hex2RGB(“#FF0”, true) would output 255,255,0

So there we have a completed function to convert hex colour values into RGB.


Leave a Reply

More Posts

Fixing SQL Reporting Services The URL has already been reserved error during Configuration

I was recently helping out a colleague with an SQL Server Reporting Services (SSRS) installation. When it came time to configuring that instance of SSRS and making it listen on port 80 for that particular site we got The URL has already been reserved warning message, navigating to the Reporting Services URLs gives us a HTTP […]

Fixing LiveUpdate was unable to find any products to update error when running Live update for Backup Exec 2010

I recently performed an install of Backup Exec 2010 R3 for a client, after doing the install and setting up the shiny new LTO-5 tape drive I decided it would be best to run LiveUpdate to make sure we were running the latest release. So I open up Backup Exec console, navigate to Tools and […]

What is new with Hyper-V in Windows Server 2012

I’ve been reading a lot lately about what people have been saying about Microsoft’s latest go at a hypervisor and many say that now with Hyper-V 2012, Microsoft is catching up to VMware in the enterprise virtualization arena (one example from ZDnet).  So what is all the fuss about…really.  I’ll identify some of the key […]