118

What would be a good way to convert hex color values like #ffffff into the single RGB values 255 255 255 using PHP?

lorem monkey
  • 3,942
  • 3
  • 35
  • 49
user123_456
  • 5,635
  • 26
  • 84
  • 140
  • Those two hex's are of the same type? First representing white, the second black... what are you trying to do? – BenOfTheNorth Mar 04 '13 at 12:56
  • `$output = sprintf('%06x', 0xffffff - hexdec(ltrim($input, '#'));` however that's probably overly simplified and you'll probably want to analyse the RGB components separately, please explain exactly what it is you are wanting to do. – DaveRandom Mar 04 '13 at 12:56
  • Your target representation example (a) doesn't form any representation of a colour I've seen and (b) doesn't meet your "without the `#`" requirement. – Quentin Mar 04 '13 at 12:56
  • `#ffffff` and `#00000` represents White and Black respectively. And for yr information `#00000` is also an Hex not an Integer. Here `f` is representing 15. – Ravi Mar 04 '13 at 12:56
  • What do you mean by *convert* and *only using an integer*? – Sverri M. Olsen Mar 04 '13 at 12:56
  • @Ravi — `#00000` is only 1+5 characters long rather than the standard 1+6, so it doesn't represent black in any scheme I know. – Quentin Mar 04 '13 at 12:57
  • @Ravi Since when does hex not represent integers? – DaveRandom Mar 04 '13 at 12:58
  • @DaveRandom I don't know more about this, but I guess if you convert ffffff to int it will return 151515151515. – Ravi Mar 04 '13 at 14:10
  • @Ravi No. You would get 2^24, because that is the integer it represents. Base conversion is done on the whole number, not each individual digit. – DaveRandom Mar 04 '13 at 14:15
  • I wrote this here, converts from basically any number value or color array to whichever type of color value it's asked for. [Convert Color Values](https://stackoverflow.com/questions/3623176/php-allocate-color-without-image-resource/55274609#55274609) – Eric Shoberg Mar 22 '19 at 14:22
  • See also [here](https://css-tricks.com/snippets/php/convert-hex-to-rgb/) catered by CSS Tricks. – user11809641 Apr 29 '21 at 21:39

18 Answers18

368

If you want to convert hex to rgb you can use sscanf:

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

Output:

#ff9900 -> 255 153 0
Clonkex
  • 3,373
  • 7
  • 38
  • 55
John
  • 3,954
  • 2
  • 11
  • 4
  • is there anything so I can have conversion like I asked in my question? Can I have output like #000000 – user123_456 Mar 04 '13 at 12:57
  • 19
    Nice clean approach with the `sscanf()`, I'm putting that one in my box of magic tricks. – DaveRandom Mar 04 '13 at 13:11
  • 12
    and for shorthand colors (`#ccc`) : `(strlen($hex) === 4) ? list($r, $g, $b) = sscanf($hex, "#%1x%1x%1x") : list($r, $g, $b) = sscanf($hex, "#%2x%2x%2x");` – iiic Sep 18 '14 at 15:37
  • up from me for the single line – Angry 84 Nov 27 '15 at 08:37
  • 5
    @iiic just writing a test for your one-liner. #ccc will return 12, 12, 12 instead of 204, 204, 204 so if you'd revert it back to hex, you'll get color #0c0c0c. – John Linhart Mar 09 '16 at 17:16
  • 1
    #F0F translates to #FF00FF so for shorthand colors list($r,$g,$b) = sscanf('#'.implode('',array_map('str_repeat',str_split(str_replace('#','',$hex)), [2,2,2])), "#%02x%02x%02x"); – aconrad Nov 15 '16 at 14:01
  • `sscanf` is such a slow function, I recommend building the rgb string manually using hexdec for the best performance – Frondor Feb 07 '17 at 00:40
  • What does %02x mean ? – Claudio Ferraro May 07 '20 at 04:36
61

Check out PHP's hexdec() and dechex() functions: http://php.net/manual/en/function.hexdec.php

Example:

$value = hexdec('ff'); // $value = 255
Blackbam
  • 17,496
  • 26
  • 97
  • 150
Niek van der Steen
  • 1,413
  • 11
  • 33
  • 14
    To use this answer to do a full conversion from a given hex value to rgb, one option is the following: `$split_hex_color = str_split( $hex_color, 2 ); $rgb1 = hexdec( $split_hex_color[0] ); $rgb2 = hexdec( $split_hex_color[1] ); $rgb3 = hexdec( $split_hex_color[2] ); ` – thenomadicmann Dec 27 '19 at 16:24
  • 1
    To account for 3 or 6 hex value input, you can do `$split_hex_color = str_split($hex_color, str_len($hex_color / 3));` – user11809641 Apr 29 '21 at 21:37
51

I made a function which also returns alpha if alpha is provided as a second parameter the code is below.

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) . ')';

TURTLE
  • 3,728
  • 4
  • 49
  • 50
46

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.

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

Here is an example the supports 4 different inputs (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)
);
kanlukasz
  • 1,103
  • 19
  • 34
arosolino
  • 1,059
  • 8
  • 10
  • 15
    Use `ltrim($colorName, '#')` instead of `$colorName` to take care of a # if it might be there – mikeytown2 Apr 25 '14 at 21:08
  • 1
    Wow, your 2nd line of code is incredible... it accepts # or not, and 3 or 6 characters. I think it's the best approach of any code examples on this page. I'm bookmarking this for future projects. – hargobind Oct 17 '19 at 04:30
22

You can use the function hexdec(hexStr: String) to get the decimal value of a hexadecimal 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)

RoyB
  • 3,104
  • 1
  • 16
  • 37
RatajS
  • 1,403
  • 1
  • 14
  • 22
7

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

IAmMilinPatel
  • 413
  • 1
  • 11
  • 19
6

I wrote a simple function like so, which supports an input value with or without beginning # and it can also take 3 or 6 character hex code input:


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

This returns an associative array that can be access as $color['red'], $color['green'], $color['blue'];

See also here from CSS Tricks.

user11809641
  • 815
  • 1
  • 11
  • 22
5

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' ) );
Martin
  • 61
  • 1
  • 3
4

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.

A short explanation:

With scanf I 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.

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)
  ];
}
Alexxus
  • 893
  • 1
  • 11
  • 25
4

Convert Color Code HEX to 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

JoyGuru
  • 1,803
  • 20
  • 11
4

Borrowing from @jhon's answer - this will return the rgb in string format with an option for opacity.

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)
gregbast1994
  • 432
  • 6
  • 16
3

Based on the high-rate answer -> 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;

}

than you can use it like

<?php
  $color = '#ffffff';
  hex2rgba($color, 0.5); 
?>
Matthias
  • 131
  • 1
  • 2
  • 10
0

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

<?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.

<?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);
}
?>
John Smith
  • 1,812
  • 1
  • 16
  • 17
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]);
Manmeet Khurana
  • 367
  • 2
  • 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])];
}
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Dharman Feb 07 '20 at 13:21
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)";
    }
Mike Smit
  • 71
  • 4
  • When answering, it's much more helpful if you explain why this is the preferred solution. The goal is to educate, not merely solve a specific problem. – the Tin Man Mar 21 '20 at 05:49
0

My solution: (Supports short notation)

$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
Starboy
  • 109
  • 5
0

If you want to get hex to RGB you can follow this:

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();
kmoser
  • 8,780
  • 3
  • 24
  • 40