RGB 转十六进制
十六进制转 RGB
函数
<?PHP
function rgb2hex2rgb($c){
if(!$c) return false;
$c = trim($c);
$out = false;
if(preg_match("/^[0-9ABCDEFabcdef\#]+$/i", $c)){
$c = str_replace('#','', $c);
$l = strlen($c) == 3 ? 1 : (strlen($c) == 6 ? 2 : false);
if($l){
unset($out);
$out[0] = $out['r'] = $out['red'] = hexdec(substr($c, 0,1*$l));
$out[1] = $out['g'] = $out['green'] = hexdec(substr($c, 1*$l,1*$l));
$out[2] = $out['b'] = $out['blue'] = hexdec(substr($c, 2*$l,1*$l));
}else $out = false;
}elseif (preg_match("/^[0-9]+(,| |.)+[0-9]+(,| |.)+[0-9]+$/i", $c)){
$spr = str_replace(array(',',' ','.'), ':', $c);
$e = explode(":", $spr);
if(count($e) != 3) return false;
$out = '#';
for($i = 0; $i<3; $i++)
$e[$i] = dechex(($e[$i] <= 0)?0:(($e[$i] >= 255)?255:$e[$i]));
for($i = 0; $i<3; $i++)
$out .= ((strlen($e[$i]) < 2)?'0':'').$e[$i];
$out = strtoupper($out);
}else $out = false;
return $out;
}
?>
输出
#FFFFFF =>
数组{
red=>255,
green=>255,
blue=>255,
r=>255,
g=>255,
b=>255,
0=>255,
1=>255,
2=>255
}
#FFCCEE =>
数组{
red=>255,
green=>204,
blue=>238,
r=>255,
g=>204,
b=>238,
0=>255,
1=>204,
2=>238
}
CC22FF =>
数组{
red=>204,
green=>34,
blue=>255,
r=>204,
g=>34,
b=>255,
0=>204,
1=>34,
2=>255
}
0 65 255 => #0041FF
255.150.3 => #FF9603
100,100,250 => #6464FA
[编辑 BY danbrown AT php DOT net - 包含多个由 (ajim1417 AT gmail DOT com) 于 2010 年 1 月 27 日修复的错误:替换 explode() 中的错字,并将 eregi() 调用更新为 preg_match()。]