[PHP] Convert hex color codes to RGB 03-22-2018, 11:48 PM
#1
I just wrote that small function for a friend of mine and thought it might be worth sharing it.
Is anybody interested in how hex color codes work and how to convert them to RGB? I mean that's just some basic stuff but many people use hex color codes everyday without even knowing how to build them.
Is anybody interested in how hex color codes work and how to convert them to RGB? I mean that's just some basic stuff but many people use hex color codes everyday without even knowing how to build them.
Code:
function convertToRGB ($hexValue)
{
if(ctype_xdigit(substr($hexValue, 1)))
{
switch(strlen($hexValue))
{
case 4:
$r = hexdec(substr($hexValue, 1, 1).substr($hexValue, 1, 1));
$g = hexdec(substr($hexValue, 2, 1).substr($hexValue, 2, 1));
$b = hexdec(substr($hexValue, 3, 1).substr($hexValue, 3, 1));
return 'rgb(' . $r . ', ' . $g . ', ' . $b . ')';
case 7:
$r = hexdec(substr($hexValue, 1, 2));
$g = hexdec(substr($hexValue, 3, 2));
$b = hexdec(substr($hexValue, 5, 2));
return 'rgb(' . $r . ', ' . $g . ', ' . $b . ')';
default:
throw new Exception('Invalid length!');
}
} else {
throw new Exception('Invalid value!');
}
}