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.
Share this post with others: