在 PHP 中将十六进制颜色转换为 RGB 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15202079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert hex color to RGB values in PHP
提问by user123_456
What would be a good way to convert hex color values like #ffffffinto the single RGB values 255 255 255using PHP?
使用 PHP将十六进制颜色值#ffffff转换为单个 RGB 值的好方法是255 255 255什么?
采纳答案by Niek van der Steen
Check out PHP's hexdec()and dechex()functions:
http://php.net/manual/en/function.hexdec.php
查看 PHPhexdec()和dechex()函数:http:
//php.net/manual/en/function.hexdec.php
Example:
例子:
$value = hexdec('ff'); // $value = 255
回答by John
回答by Jake
I made a function which also returns alpha if alpha is provided as a second parameter the code is below.
我做了一个函数,如果 alpha 作为第二个参数提供,它也会返回 alpha,代码如下。
The function
功能
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;
}
Example of function responses
函数响应示例
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
)
If you'd like to return the rgb(a) in CSS format just replace the return $rgb;line in the function with return implode(array_keys($rgb)) . '(' . implode(', ', $rgb) . ')';
如果您想以 CSS 格式返回 rgb(a),只需return $rgb;将函数中的行替换为return implode(array_keys($rgb)) . '(' . implode(', ', $rgb) . ')';
回答by arosolino
For anyone that is interested this is another very simple way of doing it. This example assumes there is exactly 6 characters and no preceding pound sign.
对于任何感兴趣的人来说,这是另一种非常简单的方法。此示例假定正好有 6 个字符且前面没有井号。
list($r, $g, $b) = array_map('hexdec', str_split($colorName, 2));
Here is an example the supports 4 different inputs (abc, aabbcc, #abc, #aabbcc):
这是一个支持 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));
回答by MSTRmt
You can use the function hexdec(hexStr: String)to get the decimal value of a hexadecimal string.
您可以使用该函数hexdec(hexStr: String)获取十六进制字符串的十进制值。
See below for an example:
请参阅下面的示例:
$split = str_split("ffffff", 2);
$r = hexdec($split[0]);
$g = hexdec($split[1]);
$b = hexdec($split[2]);
echo "rgb(" . $r . ", " . $g . ", " . $b . ")";
This will print rgb(255, 255, 255)
这将打印 rgb(255, 255, 255)
回答by Martin
My approach to take care of hex colors with or without hash, single values or pair values:
我处理带有或不带有散列、单个值或对值的十六进制颜色的方法:
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' ) );
回答by IAmMilinPatel
You can try this simple piece of code below.
你可以试试下面这段简单的代码。
list($r, $g, $b) = sscanf(#7bde84, "#%02x%02x%02x");
echo $r . "," . $g . "," . $b;
This will return 123,222,132
这将返回 123,222,132
回答by JoyGuru
Convert Color Code HEX to RGB
将颜色代码 HEX 转换为 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);
Output
输出
Array ( [r] => 255 [g] => 255 [b] => 255 )
I have found this reference from here - Convert Color Hex to RGB and RGB to Hex using PHP
我从这里找到了这个参考 - Convert Color Hex to RGB and RGB to Hex using PHP
回答by Alexxus
I've put @John's answer and @iic's comment/idea together into a function which can handle both, the usual hex color codes and the shorthand color codes.
我已将@John 的回答和@iic 的评论/想法放在一个函数中,该函数可以处理通常的十六进制颜色代码和速记颜色代码。
A short explanation:
一个简短的解释:
With scanfI read the r, g and b values from the hex color as strings. Not as hex values like in @John's answer. In case of using shorthand color codes, the r, g and b strings have to be doubled ("f" -> "ff" etc.) before converting them to decimals.
使用scanf我从十六进制颜色中读取 r、g 和 b 值作为字符串。不像@John's answer那样的十六进制值。在使用速记颜色代码的情况下,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)
];
}
回答by John Smith
try this, it converts its arguments (r, g, b) to hexadecimal html-color string #RRGGBB Arguments are converted to integers and trimmed to 0..255 range
试试这个,它将它的参数 (r, g, b) 转换为十六进制的 html-color 字符串 #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;
}
?>
oh and the other way round
哦,反过来
# character in the beginning can be omitted. Function returns array of three integers in range (0..255) or false when it fails to recognize color format.
#开头的字符可以省略。函数返回范围 (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);
}
?>

