web-dev-qa-db-fra.com

Convertir la couleur hexadécimale en valeurs RVB en PHP

Quel serait un bon moyen de convertir des valeurs de couleur hexagonales telles que #ffffff en valeurs RVB uniques 255 255 255 en utilisant PHP?

49
user123_456

Découvrez les fonctions hexdec() et dechex() de PHP: http://php.net/manual/fr/function.hexdec.php

Exemple:

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

Si vous voulez convertir hex en rgb, vous pouvez utiliser sscanf:

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

Sortie:

#ff9900 -> 255 153 0
200
John

J'ai créé une fonction qui renvoie également alpha si alpha est fourni en tant que deuxième paramètre, le code est ci-dessous.

La fonction

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;
}

Exemple de réponses de fonction

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
)

Si vous souhaitez retourner le rgb (a) au format CSS, remplacez simplement la ligne return $rgb; dans la fonction par return implode(array_keys($rgb)) . '(' . implode(', ', $rgb) . ')';.

30
Jake

C’est une autre façon très simple de le faire pour quiconque est intéressé. Cet exemple suppose qu'il y a exactement 6 caractères et aucun signe dièse précédent.

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

Voici un exemple supporte 4 entrées différentes (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));
23
arosolino

Vous pouvez utiliser la fonction hexdec(hexStr: String) pour obtenir la valeur décimale d'une chaîne hexadécimale. 

Voir ci-dessous pour un exemple: 

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

Ceci imprimera rgb(255, 255, 255)

9
MSTRmt

Mon approche consiste à prendre en charge les couleurs hexadécimales avec ou sans hachage, valeurs uniques ou valeurs de paires:

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' ) );
4
Martin

Vous pouvez essayer ce morceau de code simple ci-dessous. 

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

Cela retournera 123 222 132

4
Milin Patel

J'ai mis la réponse de @ John et le commentaire/l'idée de @ iic dans une fonction capable de gérer les deux, les codes de couleur hexagonaux habituels et les codes de couleur abrégés.

Une courte explication:

Avec scanf , je lis les valeurs r, g et b de la couleur hexadécimale sous forme de chaînes. Pas comme des valeurs hexagonales comme dans la réponse de @ John. Si vous utilisez des codes de couleur abrégés, vous devez doubler les chaînes r, g et b ("f" -> "ff" etc.) avant de les convertir en décimales.

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)
  ];
}
3
Alexxus

Convertir le code de couleur HEX en RVB

$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);

Sortie

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

J'ai trouvé cette référence ici - Convertir les couleurs Hex en RVB et RVB en Hex avec PHP

2
JoyGuru

C'est la seule solution qui a fonctionné pour moi. Certaines des réponses n'étaient pas assez cohérentes.

    function hex2rgba($color, $opacity = false) {

        $default = 'rgb(0,0,0)';

        //Return default if no color provided
        if(empty($color))
              return $default;

        //Sanitize $color if "#" is provided
            if ($color[0] == '#' ) {
                $color = substr( $color, 1 );
            }

            //Check if color has 6 or 3 characters and get values
            if (strlen($color) == 6) {
                    $hex = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
            } elseif ( strlen( $color ) == 3 ) {
                    $hex = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
            } else {
                    return $default;
            }

            //Convert hexadec to rgb
            $rgb =  array_map('hexdec', $hex);

            //Check if opacity is set(rgba or rgb)
            if($opacity){
                if(abs($opacity) > 1)
                    $opacity = 1.0;
                $output = 'rgba('.implode(",",$rgb).','.$opacity.')';
            } else {
                $output = 'rgb('.implode(",",$rgb).')';
            }

            //Return rgb(a) color string
            return $output;
    }
    //hex2rgba("#ffaa11",1)
0
Raj Sharma

essayez ceci, il convertit ses arguments (r, g, b) en hexadécimale chaîne html-color #RRGGBB Les arguments sont convertis en entiers et ajustés dans la plage 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 et l'inverse

# caractère au début peut être omis. La fonction retourne un tableau de trois entiers compris dans l'intervalle (0..255) ou false si elle ne reconnaît pas le format de couleur.

<?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);
}
?>
0
John Smith
//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]);
0
Manmeet Khurana