If you are working on a web app that does things with colours then you could find it useful to have function to convert between different colour types.
Here is a PHP snippet which allows you to convert HEX colours to RGB colours.
All you have to do is pass in the HEX colour as a parameter and it will return the RGB values as an array.
1 |
<br /> function hex2rgb($color)<br /> {<br /> list($r, $g, $b) = array($color[0].$color[1],<br /> $color[2].$color[3],<br /> $color[4].$color[5]);<br /> $r = hexdec($r); $g = hexdec($g); $b = hexdec($b);<br /> return array($r, $g, $b);<br /> }<br /> |
Improved Version
Here is an improved version of the above function to convert Hex to RGB thanks to Michael Kaiser. This function allows you to send in 6, 3, 2 or 1 digit Hex colours to the function and will still convert it to RGB.
1 |
<br /> function hex2RGB($hex) {<br /> preg_match(“/^#{0,1}([0-9a-f]{1,6})$/i”,$hex,$match);<br /> if(!isset($match[1])) {return false;} |
if(strlen($match[1]) == 6) {
list($r, $g, $b) = array($hex[0].$hex[1],$hex[2].$hex[3],$hex[4].$hex[5]);
}
elseif(strlen($match[1]) == 3) {
list($r, $g, $b) = array($hex[0].$hex[0],$hex[1].$hex[1],$hex[2].$hex[2]);
}
else if(strlen($match[1]) == 2) {
list($r, $g, $b) = array($hex[0].$hex[1],$hex[0].$hex[1],$hex[0].$hex[1]);
}
else if(strlen($match[1]) == 1) {
list($r, $g, $b) = array($hex.$hex,$hex.$hex,$hex.$hex);
}
else {
return false;
}
$color = array();
$color[‘r’] = hexdec($r);
$color[‘g’] = hexdec($g);
$color[‘b’] = hexdec($b);
return $color;
}