函数
//RGB转16进制 function RGB2Hex($r=0, $g=0, $b=0) { if($r < 0 || $g < 0 || $b < 0 || $r > 255 || $g > 255|| $b > 255){ return false; } return "#".(substr("00".dechex($r),-2)).(substr("00".dechex($g),-2)).(substr("00".dechex($b),-2)); } //16进制转RGB function Hex2RGB($hexColor) { $color = str_replace('#', '', $hexColor); if (strlen($color) > 3) { $rgb = array( 'r' => hexdec(substr($color, 0, 2)), 'g' => hexdec(substr($color, 2, 2)), 'b' => hexdec(substr($color, 4, 2)) ); } else { $color = str_replace('#', '', $hexColor); $r = substr($color, 0, 1) . substr($color, 0, 1); $g = substr($color, 1, 1) . substr($color, 1, 1); $b = substr($color, 2, 1) . substr($color, 2, 1); $rgb = array( 'r' => hexdec($r), 'g' => hexdec($g), 'b' => hexdec($b) ); } return $rgb; }
使用
我们把#333333转为RGB再转回来
$rgb = Hex2RGB('#333333'); printf("R=%d G=%d B=%d<br/>",$rgb['r'],$rgb['g'],$rgb['b']); $hex = RGB2Hex($rgb['r'],$rgb['g'],$rgb['b']); echo 'hex='.$hex;
输出
R=51 G=51 B=51 hex=#333333