使用PHP将像#ffffff
这样的十六进制颜色值转换为单个RGB值255 255 255
的好方法是什么?
答案 0 :(得分:217)
如果您想将hex转换为rgb,可以使用sscanf
:
<?php
$hex = "#ff9900";
list($r, $g, $b) = sscanf($hex, "#%02x%02x%02x");
echo "$hex -> $r $g $b";
?>
输出:
#ff9900 -> 255 153 0
答案 1 :(得分:42)
查看PHP的hexdec()
和dechex()
函数:
http://php.net/manual/en/function.hexdec.php
示例:
$value = hexdec('ff'); // $value = 255
答案 2 :(得分:32)
如果提供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) . ')';
行
答案 3 :(得分:24)
对于任何有兴趣的人来说,这是另一种非常简单的方法。此示例假设正好有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));
答案 4 :(得分:9)
您可以使用函数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)
答案 5 :(得分:4)
您可以在下面尝试这段简单的代码。
list($r, $g, $b) = sscanf(#7bde84, "#%02x%02x%02x");
echo $r . "," . $g . "," . $b;
这将返回123,222,132
答案 6 :(得分:4)
我使用或不使用散列,单值或配对值来处理十六进制颜色的方法:
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' ) );
答案 7 :(得分:3)
我把@ 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)
];
}
答案 8 :(得分:3)
我写了一个像这样的简单函数,它支持带或不带 #
开头的输入值,也可以接受 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 技巧中的 here。
答案 9 :(得分:2)
将颜色代码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);
<强>输出强>
Array ( [r] => 255 [g] => 255 [b] => 255 )
我从这里找到了这个参考 - Convert Color Hex to RGB and RGB to Hex using PHP
答案 10 :(得分:0)
//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]);
答案 11 :(得分:0)
试试这个,它将它的参数(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);
}
?>
答案 12 :(得分:0)
这是唯一对我有用的解决方案。一些答案不够一致。
# dose-toxicity probability model
# input: doseA and doseB are vectors with same size,
# doseA[i] and doseB[i] comprise a dose regimen
# output: p is a vector, p[i] is the prob. of doseA[i] and doseB[i]
probfun = function(doseA,doseB,param){
p = param[1]+param[2]*doseA+param[3]*doseB
p = exp(p)
p = 1-1/(1+p)
return(p)
}
# log-likelihood of toxicity probability
#used by function logpostT
loglike = function(doseA,doseB,param,x,n){
mu = param[1]+param[2]*doseA+param[3]*doseB
lk = sum(x*mu-n*log(1+exp(mu)))
return(lk)
}
# Cauchy prior distribution
prior_c = function(b0,mub0,scaleb0){
dcauchy(b0,mub0,scaleb0)
}
# posterior core for toxicity
#used by function mhT , to compute parameter posterior
# input:doseA,doseB,x,n are input data, vectors with same size,
# muT0,scaleT0,shapeT1,rateT1,shapeT2,rateT2 are hyperparameters for prior
logpostT = function(doseA,doseB,param,x,n,muT0,scaleT0,shapeT1,rateT1,shapeT2,rateT2){
h = loglike(doseA,doseB,param,x,n)+log(prior_c(param[1],muT0,scaleT0))+
log(prior_c(param[2],shapeT1,rateT1))+log(prior_c(param[3],shapeT2,rateT2))
return(h)
}
# candidate(proposal) density for toxicity
#used by function mhT , to provide new parameters for a new iteration
candiT = function(param,jsdb0,jsdb1,jsdb2){
a = rnorm(1,param[1],jsdb0)
b = rnorm(1,param[2],jsdb1)
c = rnorm(1,param[3],jsdb2)
return(c(a,b,c))
}
# acceptance ratio in MCMC for toxicity
#used by function mhT , to compute r in Metropolis-Hasting algorithm, likelihood_new/likelihood_old*prior_new/prior_old
ratioT = function(doseA,doseB,x,n,b,bs,muT0,scaleT0,shapeT1,rateT1,shapeT2,rateT2){
r = exp(sum(x*((bs[1]-b[1])+doseA*(bs[2]-b[2])+doseB*(bs[3]-b[3])))-
sum(n*(log(1+exp(bs[1]+doseA*bs[2]+doseB*bs[3]))-log(1+exp(b[1]+doseA*b[2]+doseB*b[3])))))*
prior_c(bs[1],muT0,scaleT0)/prior_c(b[1],muT0,scaleT0)*
prior_c(bs[2],shapeT1,rateT1)/prior_c(b[2],shapeT1,rateT1)*prior_c(bs[3],shapeT2,rateT2)/prior_c(b[3],shapeT2,rateT2)
if(is.na(r)==T) r=Inf
return(r)
}
# Metropolis-Hasting algorithm for toxicity
mhT = function(doseA,doseB,x,n,muT0,scaleT0,shapeT1,rateT1,shapeT2,rateT2,jsdb0,jsdb1,jsdb2,size,burn,thin){
start = c(-5,5,5)
b_pre = start
n_var = length(b_pre)
ac = matrix(0,size,n_var)
draws = matrix(NA,size,n_var)
post = c()
for (i in 1:size) {
b_cand = candiT(b_pre,jsdb0,jsdb1,jsdb2)
b_old = b_pre
#sequential updated every parameter in each iteration
for (j in 1:n_var){
#give the b_star based on the b_old and b_cand
if (j==1) {
b_star = c(b_cand[j],b_old[(j+1):n_var])
} else if (j==n_var) {
b_star = c(b_old[1:(j-1)],b_cand[j])
} else {
b_star = c(b_old[1:(j-1)],b_cand[j],b_old[(j+1):n_var])
}
#calculate ratio and determine whether to accept or not
r = ratioT(doseA,doseB,x,n,b_old,b_star,muT0,scaleT0,shapeT1,rateT1,shapeT2,rateT2)
if (runif(1)<r) {
b_new = b_star
ac[i,j]=1
}else {
b_new = b_old
ac[i,j]=0
}
b_old = b_new
}
draws[i,] = b_new
post[i] = logpostT(doseA,doseB,draws[i,],x,n,muT0,scaleT0,shapeT1,rateT1,shapeT2,rateT2)
b_pre = b_new
}
return(list(draws=draws[seq(floor(size*burn)+1,size,thin),],post=post[seq(floor(size*burn)+1,size,thin)],ac=apply(ac,2,sum)))
}
答案 13 :(得分:0)
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])];
}
答案 14 :(得分:0)
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)";
}
答案 15 :(得分:0)
我的解决方案:(支持缩写)
$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
答案 16 :(得分:0)
从@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)