在 PHP 中将十六进制颜色转换为 RGB 值


Convert hex color to RGB values in PHP

使用 PHP 将十六进制颜色值(如 #ffffff(转换为单个 RGB 值255 255 255的好方法是什么?

如果要将十六进制转换为 rgb,可以使用 sscanf:

<?php
$hex = "#ff9900";
list($r, $g, $b) = sscanf($hex, "#%02x%02x%02x");
echo "$hex -> $r $g $b";
?>

输出:

#ff9900 -> 255 153 0

查看 PHP 的hexdec()dechex()函数:http://php.net/manual/en/function.hexdec.php

例:

$value = hexdec('ff'); // $value = 255

我做了一个函数,如果提供alpha作为第二个参数,代码如下,它也返回alpha。

函数

function hexToRgb($hex, $alpha = false) {
   $hex      = str_replace('#', '', $hex);
   $length   = strlen($hex);
   $rgb['r'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0));
   $rgb['g'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0));
   $rgb['b'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0));
   if ( $alpha ) {
      $rgb['a'] = $alpha;
   }
   return $rgb;
}

函数响应示例

print_r(hexToRgb('#19b698'));
Array (
   [r] => 25
   [g] => 182
   [b] => 152
)
print_r(hexToRgb('19b698'));
Array (
   [r] => 25
   [g] => 182
   [b] => 152
)
print_r(hexToRgb('#19b698', 1));
Array (
   [r] => 25
   [g] => 182
   [b] => 152
   [a] => 1
)
print_r(hexToRgb('#fff'));
Array (
   [r] => 255
   [g] => 255
   [b] => 255
)

如果您想以 CSS 格式返回 rgb(a(,只需将函数中的return $rgb;行替换为 return implode(array_keys($rgb)) . '(' . implode(', ', $rgb) . ')';

对于任何感兴趣的人来说,这是另一种非常简单的方法。此示例假定正好有 6 个字符,并且前面没有井号。

list($r, $g, $b) = array_map('hexdec', str_split($colorName, 2));

下面是一个支持4种不同输入(abc,aabbcc,#abc,#aabbcc(的示例:

list($r, $g, $b) = array_map(
  function ($c) {
    return hexdec(str_pad($c, 2, $c));
  },
  str_split(ltrim($colorName, '#'), strlen($colorName) > 4 ? 2 : 1)
);

可以使用函数 hexdec(hexStr: String) 获取十六进制字符串的十进制值。

有关示例,请参见下文:

$split = str_split("ffffff", 2);
$r = hexdec($split[0]);
$g = hexdec($split[1]);
$b = hexdec($split[2]);
echo "rgb(" . $r . ", " . $g . ", " . $b . ")";

这将打印rgb(255, 255, 255)

您可以在下面尝试这段简单的代码。

list($r, $g, $b) = sscanf(#7bde84, "#%02x%02x%02x");
echo $r . "," . $g . "," . $b;

这将返回 123,222,132

我写了一个简单的函数,它支持带或不带开头#的输入值,它也可以接受 3 或 6 个字符的十六进制代码输入:


function hex2rgb( $color ) {
    if ($color[0] == '#') {
        $color = substr($color, 1);
    }
    list($r, $g, $b) = array_map("hexdec", str_split($color, (strlen( $color ) / 3)));
    return array( 'red' => $r, 'green' => $g, 'blue' => $b );
}

这将返回一个关联数组,该数组可以作为$color['red']$color['green']$color['blue']访问;

另请参阅此处的 CSS Tricks。

我处理

带有或不带有哈希、单个值或成对值的十六进制颜色的方法:

function hex2rgb ( $hex_color ) {
    $values = str_replace( '#', '', $hex_color );
    switch ( strlen( $values ) ) {
        case 3;
            list( $r, $g, $b ) = sscanf( $values, "%1s%1s%1s" );
            return [ hexdec( "$r$r" ), hexdec( "$g$g" ), hexdec( "$b$b" ) ];
        case 6;
            return array_map( 'hexdec', sscanf( $values, "%2s%2s%2s" ) );
        default:
            return false;
    }
}
// returns array(255,68,204)
var_dump( hex2rgb( '#ff44cc' ) );
var_dump( hex2rgb( 'ff44cc' ) );
var_dump( hex2rgb( '#f4c' ) );
var_dump( hex2rgb( 'f4c' ) );
// returns false
var_dump( hex2rgb( '#f4' ) );
var_dump( hex2rgb( 'f489' ) );

我将@John的答案和@iic的评论/想法放在一个函数中,该函数可以同时处理通常的十六进制颜色代码和速记颜色代码。

简短的解释:

使用 scanf,我从十六进制颜色中读取 r、g 和 b 值作为字符串。不像@John的答案那样十六进制值。在使用速记颜色代码的情况下,r、g 和 b 字符串在转换为小数之前必须加倍("f"->"ff"等(。

function hex2rgb($hexColor)
{
  $shorthand = (strlen($hexColor) == 4);
  list($r, $g, $b) = $shorthand? sscanf($hexColor, "#%1s%1s%1s") : sscanf($hexColor, "#%2s%2s%2s");
  return [
    "r" => hexdec($shorthand? "$r$r" : $r),
    "g" => hexdec($shorthand? "$g$g" : $g),
    "b" => hexdec($shorthand? "$b$b" : $b)
  ];
}

将颜色代码十六进制转换为 RGB

$color = '#ffffff';
$hex = str_replace('#','', $color);
if(strlen($hex) == 3):
   $rgbArray['r'] = hexdec(substr($hex,0,1).substr($hex,0,1));
   $rgbArray['g'] = hexdec(substr($hex,1,1).substr($hex,1,1));
   $rgbArray['b'] = hexdec(substr($hex,2,1).substr($hex,2,1));
else:
   $rgbArray['r'] = hexdec(substr($hex,0,2));
   $rgbArray['g'] = hexdec(substr($hex,2,2));
   $rgbArray['b'] = hexdec(substr($hex,4,2));
endif;
print_r($rgbArray);

输出

Array ( [r] => 255 [g] => 255 [b] => 255 )

我从这里找到了这个参考 - 使用 PHP 将颜色十六进制转换为 RGB 和 RGB 转换为十六进制

借用@jhon的答案 - 这将以字符串格式返回 RGB,并带有不透明度选项。

function convert_hex_to_rgba($hex, $opacity = 1){
    list($r, $g, $b) = sscanf($hex, "#%02x%02x%02x");
    return sprintf('rgba(%s, %s, %s, %s)', $r, $g, $b, $opacity);
}
convert_hex_to_rgba($bg_color, 0.9) // rgba(2,2,2,0.9)

基于高速率答案 -> https://stackoverflow.com/a/15202130/3884001

function hex2rgba( $color, $opacity ) {
    list($r, $g, $b) = sscanf($color, "#%02x%02x%02x");
    $output = "rgba($r, $g, $b, $opacity)";
    return $output;
}

比你可以像使用它一样

<?php
  $color = '#ffffff';
  hex2rgba($color, 0.5); 
?>

试试这个,它会将其参数(r,g,b(转换为十六进制HTML颜色字符串 #RRGGBB 参数转换为整数并修剪为 0..255 范围

<?php
function rgb2html($r, $g=-1, $b=-1)
{
    if (is_array($r) && sizeof($r) == 3)
        list($r, $g, $b) = $r;
    $r = intval($r); $g = intval($g);
    $b = intval($b);
    $r = dechex($r<0?0:($r>255?255:$r));
    $g = dechex($g<0?0:($g>255?255:$g));
    $b = dechex($b<0?0:($b>255?255:$b));
    $color = (strlen($r) < 2?'0':'').$r;
    $color .= (strlen($g) < 2?'0':'').$g;
    $color .= (strlen($b) < 2?'0':'').$b;
    return '#'.$color;
}
?>

哦,反过来

#开头的字符可以省略。函数返回范围为 (0..255( 的三个整数的数组,当它无法识别颜色格式时返回 false。

<?php
function html2rgb($color)
{
    if ($color[0] == '#')
        $color = substr($color, 1);
    if (strlen($color) == 6)
        list($r, $g, $b) = array($color[0].$color[1],
                                 $color[2].$color[3],
                                 $color[4].$color[5]);
    elseif (strlen($color) == 3)
        list($r, $g, $b) = array($color[0].$color[0], $color[1].$color[1], $color[2].$color[2]);
    else
        return false;
    $r = hexdec($r); $g = hexdec($g); $b = hexdec($b);
    return array($r, $g, $b);
}
?>
//if u want to convert rgb to hex
$color='254,125,1';
$rgbarr=explode(",", $color);
echo sprintf("#%02x%02x%02x", $rgbarr[0], $rgbarr[1], $rgbarr[2]);
function RGB($hex = '')
{
    $hex = str_replace('#', '', $hex);
    if(strlen($hex) > 3) $color = str_split($hex, 2);
    else $color = str_split($hex);
    return [hexdec($color[0]), hexdec($color[1]), hexdec($color[2])];
}
Enjoy    
public static function hexColorToRgba($hex, float $a){
        if($a < 0.0 || $a > 1.0){
            $a = 1.0;
        }
        for ($i = 1; $i <= 5; $i = $i+2){
            $rgb[] = hexdec(substr($hex,$i,2));
        }
        return"rgba({$rgb[0]},{$rgb[1]},{$rgb[2]},$a)";
    }

我的解决方案:(支持短符号(

$color = "#0ab";
$colort = trim( $color );
if( $colort and is_string( $color ) and preg_match( "~^#?([abcdef0-9]{3}|[abcdef0-9]{6})$~ui", $colort ))
{
    if( preg_match( "~^#?[abcdef0-9]{3}$~ui", $colort ))
    {
        $hex = trim( $colort, "#" );
        list( $hexR, $hexG, $hexB ) = str_split( $hex );
        $hexR .= $hexR;
        $hexG .= $hexG;
        $hexB .= $hexB;
    }
    else
    {
        $hex = trim( $colort, "#" );
        list( $hexR, $hexG, $hexB ) = str_split( $hex, 2 );
    }
    $colorR = hexdec( $hexR );
    $colorG = hexdec( $hexG );
    $colorB = hexdec( $hexB );
}
// Test
echo $colorR ."/" .$colorG ."/" .$colorB;
// → 0/170/187

如果你想让十六进制到RGB,你可以按照这个操作:

class RGB
{        
    private $color; //#ff0000
    private $red;
    private $green;
    private $blue;
    public function __construct($colorCode = '')
    {
        $this->color = ltrim($colorCode, '#');
        $this->parseColor();
    }
    public function readRGBColor()
    {
        echo "Red = {$this->red}'nGreen = {$this->green}'nBlue = {$this->blue}";
    }
    private function parseColor()
    {
        if ($this->color) {
            list($this->red, $this->green, $this->blue) = sscanf($this->color, '%02x%02x%02x');
        } else {
            list($this->red, $this->green, $this->blue) = array(0, 0, 0);
        }
    }
}
$myColor = new RGB("#ffffff");
$myColor->readRGBColor();