Converter a cor hex para valores RGB em PHP
Qual seria uma boa maneira de converter valores de cor hex como #ffffff
nos valores RGB únicos 255 255 255
usando o PHP?
11 answers
Confira as funções de PHP hexdec()
e dechex()
:
http://php.net/manual/en/function.hexdec.php
Exemplo:
$value = hexdec('ff'); // $value = 255
Se quiser converter o hex em rgb, poderá usar sscanf
:
<?php
$hex = "#ff9900";
list($r, $g, $b) = sscanf($hex, "#%02x%02x%02x");
echo "$hex -> $r $g $b";
?>
Resultado:
#ff9900 -> 255 153 0
Fiz uma função que também devolve Alfa se o Alfa for fornecido como segundo parâmetro, o código está em baixo.
A função
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;
}
Exemplo de respostas de funções
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
)
Se quiser devolver o rgb (a) no formato CSS, basta substituir a linha return $rgb;
na função comreturn implode(array_keys($rgb)) . '(' . implode(', ', $rgb) . ')';
list($r, $g, $b) = array_map('hexdec', str_split($colorName, 2));
Aqui está um exemplo que suporta 4 entradas diferentes (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));
Coloquei a resposta de @John e a ideia do @iic numa função que pode lidar com ambos, os códigos de cor hex habituais e os códigos de cor estenografia.
Uma breve explicação:
Com scanf li os valores r, g e b da cor hex como cordas. Não como os valores de hex como na resposta de @John. No caso de usar códigos de cor estenografia, as cadeias r, g E b têm que ser dobradas ("f" -> "ff" etc.) antes de convertê-los em decimais.
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)
];
}
A minha abordagem para tratar das cores hex com ou sem hash, valores únicos ou valores de pares:
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' ) );
Você pode tentar este simples pedaço de código abaixo.
list($r, $g, $b) = sscanf(#7bde84, "#%02x%02x%02x");
echo $r . "," . $g . "," . $b;
Isto vai devolver 123.222.132
Pode usar a função hexdec(hexStr: String)
para obter o valor decimal de uma cadeia hexadecimal.
Ver abaixo um exemplo:
$split = str_split("ffffff", 2);
$r = hexdec($split[0]);
$g = hexdec($split[1]);
$b = hexdec($split[2]);
echo "rgb(" . $r . ", " . $g . ", " . $b . ")";
Isto irá imprimir rgb(255, 255, 255)
Converter o código de cores HEX para 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);
Resultado
Array ( [r] => 255 [g] => 255 [b] => 255 )
Encontrei esta referência aqui - converta o Hex de cores para RGB e RGB Para Hex usando o PHP
Tente isso, ele converte seus argumentos (r, g, b) Para hexadecimal html-color string #RRGGBB argumentos são convertidos para inteiros e aparados para 0..255 intervalo
<?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 e ao contrário
# o carácter no início pode ser omitido. A função devolve uma lista de três inteiros no intervalo (0..255) ou falso quando não reconhece o formato de cor.
<?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]);