用法:

使用“rgb2hex2rgb()”函数,如下所示。

$hexString = rgb2hex2rgb('255,255,255');
$rgbArray = rgb2hex2rgb('#FFFFFF');

'rgb2hex2rgb()' 函数如下:

/**
*
*
**/
function rgb2hex2rgb($color){ 
   if(!$color) return false; 
   $color = trim($color); 
   $result = false; 
  if(preg_match("/^[0-9ABCDEFabcdef\#]+$/i", $color)){
      $hex = str_replace('#','', $color);
      if(!$hex) return false;
      if(strlen($hex) == 3):
         $result['r'] = hexdec(substr($hex,0,1).substr($hex,0,1));
         $result['g'] = hexdec(substr($hex,1,1).substr($hex,1,1));
         $result['b'] = hexdec(substr($hex,2,1).substr($hex,2,1));
      else:
         $result['r'] = hexdec(substr($hex,0,2));
         $result['g'] = hexdec(substr($hex,2,2));
         $result['b'] = hexdec(substr($hex,4,2));
      endif;       
   }elseif (preg_match("/^[0-9]+(,| |.)+[0-9]+(,| |.)+[0-9]+$/i", $color)){ 
      $rgbstr = str_replace(array(',',' ','.'), ':', $color); 
      $rgbarr = explode(":", $rgbstr);
      $result = '#';
      $result .= str_pad(dechex($rgbarr[0]), 2, "0", STR_PAD_LEFT);
      $result .= str_pad(dechex($rgbarr[1]), 2, "0", STR_PAD_LEFT);
      $result .= str_pad(dechex($rgbarr[2]), 2, "0", STR_PAD_LEFT);
      $result = strtoupper($result); 
   }else{
      $result = false;
   }

   return $result; 
}
在PHP中如何转换颜色的格式

本文将解释如何使用 PHP 将颜色代码从 HEX 转换为 RGB 或者 HEX 到 RGB。
我们创建了一个 PHP 函数,用于将颜色代码转换为 RGB 或者 HEX。

'rgb2hex2rgb()' 函数使颜色转换变得简单。

参数:

'rgb2hex2rgb()' 函数接受一个参数 ( '$color' ) 和两种类型的值 RGB 或者 HEX。

  • '$color' => 必需,我们要从中转换。
  • RGB => 255,255,255 或者 255 255 255 或者 255.255.255
  • 十六进制 => #FFFFFF 或者 FFFFFF

返回值:

如果十六进制颜色代码被传递到 '$color' 参数,则以数组形式返回 RGB 格式的颜色代码。
如果将 RGB 颜色代码传递给 '$color' 参数,则将十六进制格式的颜色代码作为字符串返回。

  • RGB => Array( [r] => 255 [g] => 255 [b] => 255)
  • HEX => #FFFFFF
日期:2020-06-02 22:15:26 来源:oir作者:oir