RGB颜色和十六进制颜色互转

  1. /**
  2.    * RGB转 十六进制
  3.    * @param $rgb RGB颜色的字符串 如:rgb(255,255,255);
  4.    * @return string 十六进制颜色值 如:#FFFFFF
  5.    */
  6.   function RGBToHex($rgb){
  7.     $regexp = "/^rgb\(([0-9]{0,3})\,\s*([0-9]{0,3})\,\s*([0-9]{0,3})\)/";
  8.     $re = preg_match($regexp, $rgb, $match);
  9.     $re = array_shift($match);
  10.     $hexColor = "#";
  11.     $hex = array(‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’);
  12.     for ($i = 0; $i < 3; $i++) {
  13.       $r = null;
  14.       $c = $match[$i];
  15.       $hexAr = array();
  16.       while ($c > 16) {
  17.         $r = $c % 16;
  18.         $c = ($c / 16) >> 0;
  19.         array_push($hexAr, $hex[$r]);
  20.       }
  21.       array_push($hexAr, $hex[$c]);
  22.       $ret = array_reverse($hexAr);
  23.       $item = implode(”, $ret);
  24.       $item = str_pad($item, 2, ‘0’, STR_PAD_LEFT);
  25.       $hexColor .= $item;
  26.     }
  27.     return $hexColor;
  28.   }
  29.   /**
  30.    * 十六进制 转 RGB
  31.    */
  32.   function hex2rgb($hexColor) {
  33.     $color = str_replace(‘#’, ”, $hexColor);
  34.     if (strlen($color) > 3) {
  35.       $rgb = array(
  36.         ‘r’ => hexdec(substr($color, 0, 2)),
  37.         ‘g’ => hexdec(substr($color, 2, 2)),
  38.         ‘b’ => hexdec(substr($color, 4, 2))
  39.       );
  40.     } else {
  41.       $color = $hexColor;
  42.       $r = substr($color, 0, 1) . substr($color, 0, 1);
  43.       $g = substr($color, 1, 1) . substr($color, 1, 1);
  44.       $b = substr($color, 2, 1) . substr($color, 2, 1);
  45.       $rgb = array(
  46.         ‘r’ => hexdec($r),
  47.         ‘g’ => hexdec($g),
  48.         ‘b’ => hexdec($b)
  49.       );
  50.     }
  51.     return $rgb;
  52.   }

复制代码

发表回复