•

Check out our Community Blogs

Register and join over 40,000 other developers!

### Recent Blog Entries

• phi

I love this community !

• JackJames

hi i am jack i am seo expert jack james would love you to read new post

# RGB to hex colors and hex colors to RGB - PHP

12 replies to this topic

### #1 Vswe

Vswe

• Expert Member
• 1989 posts
• Programming Language:Java, C#, PHP, Python, JavaScript, PL/SQL, Visual Basic .NET, Lua, ActionScript

Posted 13 November 2009 - 05:50 PM

When using Colors in HTML and CSS you need to use a hexadecimal color (something like #FFFFFF) which is the base 16 value from the RGB color scale. Sometimes you'll need to use the RGB scale instead, for example when allocating colors when drawing images with PHP and you maybe just prefer to write it in one of the ways even though you need to have it in the other. I will in this tutorial show you how you can make two functions(fromRGB and toRGB) which can convert hexadecimal colors to RGB colors and vice versa.

We will begin with converting RGB colors to the hexadecimal colors you use in HTML. To make it simple to use we'll have a function with one parameter for each of the Red, Green and Blue values which could look something like this:

```function fromRGB(\$R, \$G, \$B){  }
```

So now the function will accept all required values so we'll be able to convert it to the value we want. These 3 values will need to be converted from base 10 to base 16. To use this we'll use something called "dechex()" which will convert decimal values to hexadecimal values, we can use it like this:

``` function fromRGB(\$R, \$G, \$B){  \$R=dechex(\$R);  \$G=dechex(\$G);  \$B=dechex(\$B); }
```

Now we'll convert the values to hexadecimal, but the HTML colors has 6 digits(2 for each value) and if we have a low value this will be converted to a one digit number, not a 2 digit number. Since we always wants it to be 2 digits we have to add a leading 0 to the 1 digit numbers. A solution for this is to use "strlen" to get the length of them, is the length is lower then 2 we have to add a leading 0. So if we add this to the function it will look like this:´

```function fromRGB(\$R, \$G, \$B){  \$R=dechex(\$R); If (strlen(\$R)<2) \$R='0'.\$R;   \$G=dechex(\$G); If (strlen(\$G)<2) \$G='0'.\$G;  \$B=dechex(\$B); If (strlen(\$B)<2) \$B='0'.\$B; }
```

Now we've already made the main thing so we should now return the values together. By adding a # in the beginning it will look as it should. The function will now look like this:

```function fromRGB(\$R, \$G, \$B){  \$R=dechex(\$R); If (strlen(\$R)<2) \$R='0'.\$R;   \$G=dechex(\$G); If (strlen(\$G)<2) \$G='0'.\$G;  \$B=dechex(\$B); If (strlen(\$B)<2) \$B='0'.\$B;  return '#' . \$R . \$G . \$B; }
```

Now if we want to test it we can do it like this:

```echo fromRGB(115,25,190);
```

And then the result should be:

`#7319be`

Now we also want to do it the other way around. This time we will only use one parameter, the parameter containing the hexadecimal color:

```function toRGB(\$Hex){   }
```

We only want the actual value, so if the color is starting with a "#" we want to remove it, to test if it does we will use substr to get the first character, if it is "#" we will just remove it.

```function toRGB(\$Hex){   if (substr(\$Hex,0,1) == "#")    \$Hex = substr(\$Hex,1);   }
```

Now we will always only have the actual value, now we want to split this up into the red, the green and the blue values. We can use substr here too to get the different parts. The two first characters is stored in the variable called \$R, character number 3 and 4 is stored in \$G and lastly the 5th and the 6th character is stored in the last variable \$B.

```function toRGB(\$Hex){   if (substr(\$Hex,0,1) == "#")    \$Hex = substr(\$Hex,1);   \$R = substr(\$Hex,0,2);\$G = substr(\$Hex,2,2);\$B = substr(\$Hex,4,2);}
```

\$R, \$G and \$B does now contain the values we want, but they are still hexadecimal. To convert their 16 base to the 10 base we want we will have to use "hexdec()" which is the opposite to "dechex()" which we used earlier when converting it the other way. If we use this on all the three values we will get the values we want.

```function toRGB(\$Hex){   if (substr(\$Hex,0,1) == "#")    \$Hex = substr(\$Hex,1);   \$R = substr(\$Hex,0,2);\$G = substr(\$Hex,2,2);\$B = substr(\$Hex,4,2);\$R = hexdec(\$R);\$G = hexdec(\$G);\$B = hexdec(\$B);}
```

The 3 variables does now contains the decimal values we want to get. Now we should only return this in a good way. One way is to store them all in a variable called \$RGB and ten return that one. The whole function will then look like this:

```function toRGB(\$Hex){   if (substr(\$Hex,0,1) == "#")    \$Hex = substr(\$Hex,1);        \$R = substr(\$Hex,0,2);\$G = substr(\$Hex,2,2);\$B = substr(\$Hex,4,2);\$R = hexdec(\$R);\$G = hexdec(\$G);\$B = hexdec(\$B);\$RGB['R'] = \$R;\$RGB['G'] = \$G;\$RGB['B'] = \$B;return \$RGB;}
```

Now we want to try if it works, to do this you have to do something like this:

```\$RGB = toRGB("#49fe3a");echo "R = " . \$RGB['R'] . "<br />";echo "G = " . \$RGB['G'] . "<br />";echo "B = " . \$RGB['B'] . "<br />";
```

Which would give us the output:

```R = 73
G = 254
B = 58```

So if we now want to test if these two function actually works we can use them together and wee if we will get he original value back, the code for taking a hexadecimal color, convert it to RGB and then convert it back looks like this:

```\$RGB =  toRGB("#0076cc");echo fromRGB(\$RGB['R'], \$RGB['G'], \$RGB['B']);
```

And the output is...

`#0076cc`

...exactly the same so therefor we know that it's working.

That was everything I had for this tutorial, I hope you enjoyed it
• 2

### #2 Guest_Jordan_*

Guest_Jordan_*
• Guest

Posted 14 November 2009 - 05:37 AM

Very useful function! +rep
• 0

### #3 WingedPanther73

WingedPanther73

A spammer's worst nightmare

• Moderator
• 17757 posts
• Location:Upstate, South Carolina
• Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
• Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 14 November 2009 - 02:21 PM

Interesting. +rep
• 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/

### #4 technica

technica

CC Regular

• Just Joined
• 43 posts

Posted 28 December 2009 - 11:13 PM

Good one for those who plays a lot with HTML and need to handle the colors with coding.
• 0

### #5 DiscoStu

DiscoStu

CC Lurker

• Just Joined
• 7 posts

Posted 21 March 2010 - 06:50 PM

This is brilliant! Thankyou

Now, i just need one of these that converts to Pantone colours, and I'll be set ;-)
• 0

### #6 davitz38

davitz38

CC Lurker

• Just Joined
• 2 posts

Posted 10 April 2010 - 10:40 AM

For some of you looking for an online tool to convert hex to rgb and convert rgb to hex, these two are pretty good
Pretty cool!
David
• 0

### #7 Alexander

Alexander

YOL9

• Moderator
• 3963 posts
• Location:Vancouver, Eh! Cleverness: 200
• Programming Language:C, C++, PHP, Assembly

Posted 06 October 2010 - 07:55 AM

I do it the pro way (yes I like fiddling with bits):
```function rgb2hex(\$r, \$g, \$b) {
return '#' . sprintf("%x", (\$r << 16) + (\$g << 8) + \$b));
}
function hex2rgb(\$hex) {
if(\$hex[0] == '#') {
unset(\$hex[0]);
}
\$dec = sprintf("%d", \$hex);
return  (\$dec >> 16) % 255 . ', ' . (\$dec >> 8) % 255 . ', ' . (\$dec % 255);
}
```
(atleast in princible) thousands of times faster than your functions.
• 0

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.

### #8 Vswe

Vswe

• Expert Member
• 1989 posts
• Programming Language:Java, C#, PHP, Python, JavaScript, PL/SQL, Visual Basic .NET, Lua, ActionScript

Posted 06 October 2010 - 08:18 AM

I do it the pro way (yes I like fiddling with bits):

```//code omitted
```
(atleast in princible) thousands of times faster than your functions.

You should make a tutorial about it for anyone that doesn't understand how it works but want to use it
• 0

### #9 Alexander

Alexander

YOL9

• Moderator
• 3963 posts
• Location:Vancouver, Eh! Cleverness: 200
• Programming Language:C, C++, PHP, Assembly

Posted 06 October 2010 - 09:17 AM

Yeah. We do need a good bit fiddling tutorial, I mean you can work with hex and IPs and RGBs and piles of neat things with it.
• 0

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.

### #10 VinnyMrvdogBenson

VinnyMrvdogBenson

CC Lurker

• New Member
• 3 posts

Posted 24 January 2014 - 07:39 AM

I know this was over 3 years ago, but for come reason if I do

```echo RGBtoHex(255,255,255)
```

it returns #ffff19

any Ideas why?

I am using this code

```function RGBToHex(\$r, \$g, \$b) {
return sprintf("%x", (\$r << 16) + (\$g << 8) + \$b);
}```

Edited by VinnyMrvdogBenson, 24 January 2014 - 07:45 AM.

• 0

### #11 Alexander

Alexander

YOL9

• Moderator
• 3963 posts
• Location:Vancouver, Eh! Cleverness: 200
• Programming Language:C, C++, PHP, Assembly

Posted 24 January 2014 - 08:35 PM

I know this was over 3 years ago, but for come reason if I do

```echo RGBtoHex(255,255,255)
```
it returns #ffff19

Using a bit of math, 19 in base 16 is 25 in base 10, this likely points to a typographical error on your part of "25" rather than "255".

Alexander.
• 0

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.

### #12 VinnyMrvdogBenson

VinnyMrvdogBenson

CC Lurker

• New Member
• 3 posts

Posted 25 January 2014 - 08:36 AM

Thanks, I will check my code for any mistakes

• 0

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download