PHP Function to convert Hex to Rgb Color Code and ViceVersa

by Sasikumar 2014-03-10 19:05:47

Function to covert HEX code to RGB color Code:
function hex2rgb($hex) {
$hex = str_replace("#", "", $hex);

if(strlen($hex) == 3) {
$r = hexdec(substr($hex,0,1).substr($hex,0,1));
$g = hexdec(substr($hex,1,1).substr($hex,1,1));
$b = hexdec(substr($hex,2,1).substr($hex,2,1));
} else {
$r = hexdec(substr($hex,0,2));
$g = hexdec(substr($hex,2,2));
$b = hexdec(substr($hex,4,2));
}
$rgb = array($r, $g, $b);
//return implode(",", $rgb); // returns the rgb values separated by commas
return $rgb; // returns an array with the rgb values
}
Example Usage :
$rgb = hex2rgb("#cc0");
print_r($rgb)
Output :
Array ( [0] => 204 [1] => 204 [2] => 0 )

Function to covert RGB code to HEX color Code:
function rgb2hex($rgb) {
$hex = "#";
$hex .= str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb[2]), 2, "0", STR_PAD_LEFT);

return $hex; // returns the hex value including the number sign (#)
}
Example Usage :
$rgb = array( 255, 255, 255 );
$hex = rgb2hex($rgb);
echo $hex;
Output :
#ffffff

Tagged in:

953
like
0
dislike
0
mail
flag

You must LOGIN to add comments