+ Reply to Thread
Results 1 to 9 of 9

Thread: RGB to hex colors and hex colors to RGB - PHP

  1. #1
    Join Date
    Apr 2009
    Location
    Uppsala, Sweden
    Posts
    9,547
    Blog Entries
    5
    Rep Power
    98

    RGB to hex colors and hex colors to RGB - PHP

    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.






    From RGB to Hexadecimal

    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:



    Code:
    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:



    Code:
     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:´





    Code:
    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:

    Code:
    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:

    Code:
    echo fromRGB(115,25,190); 
    And then the result should be:

    Code:
    #7319be









    From Hexadecimal to RGB


    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:


    Code:
    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.



    Code:
    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.


    Code:
    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.


    Code:
    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:

    Code:
    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:

    Code:
    $RGB toRGB("#49fe3a");
    echo 
    "R = " $RGB['R'] . "<br />";
    echo 
    "G = " $RGB['G'] . "<br />";
    echo 
    "B = " $RGB['B'] . "<br />"
    Which would give us the output:

    Code:
    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:

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

    And the output is...


    Code:
    #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. CODECALL Circuit advertisement
    Join Date
    Always
    Location
    Advertising world
    Posts
    Many

     
  3. #2
    Jordan Guest

    Re: RGB to hex colors and hex colors to RGB - PHP

    Very useful function! +rep

  4. #3
    Join Date
    Jul 2006
    Posts
    16,491
    Blog Entries
    75
    Rep Power
    143

    Re: RGB to hex colors and hex colors to RGB - PHP

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

  5. #4
    technica's Avatar
    technica is offline Learning Programmer
    Join Date
    Oct 2009
    Posts
    64
    Rep Power
    0

    Re: RGB to hex colors and hex colors to RGB - PHP

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

  6. #5
    DiscoStu is offline Newbie
    Join Date
    Mar 2010
    Posts
    7
    Rep Power
    0

    Re: RGB to hex colors and hex colors to RGB - PHP

    This is brilliant! Thankyou

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

  7. #6
    davitz38 is offline Newbie
    Join Date
    Feb 2010
    Posts
    2
    Rep Power
    0

    Re: RGB to hex colors and hex colors to RGB - PHP

    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

  8. #7
    Join Date
    Jun 2010
    Location
    Vancouver, Eh.
    Posts
    4,020
    Blog Entries
    7
    Rep Power
    39

    Re: RGB to hex colors and hex colors to RGB - PHP

    I do it the pro way (yes I like fiddling with bits):
    Code:
    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.
    Be sure to read the updated FAQ || Health is achieved through 10,000 different steps.
    A textual description can be only part of your question, be sure to provide sample results, errors and your platform in the appropriate forums while asking.

  9. #8
    Join Date
    Apr 2009
    Location
    Uppsala, Sweden
    Posts
    9,547
    Blog Entries
    5
    Rep Power
    98

    Re: RGB to hex colors and hex colors to RGB - PHP

    Quote Originally Posted by Nullw0rm View Post
    I do it the pro way (yes I like fiddling with bits):
    Code:
    //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

  10. #9
    Join Date
    Jun 2010
    Location
    Vancouver, Eh.
    Posts
    4,020
    Blog Entries
    7
    Rep Power
    39

    Re: RGB to hex colors and hex colors to RGB - PHP

    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.
    Be sure to read the updated FAQ || Health is achieved through 10,000 different steps.
    A textual description can be only part of your question, be sure to provide sample results, errors and your platform in the appropriate forums while asking.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Colors in VB.NET
    By Vswe in forum Visual Basic Tutorials
    Replies: 5
    Last Post: 09-23-2010, 10:46 PM
  2. Convert 256 colors to 16 colors - BMP Image
    By spyrytus in forum C and C++
    Replies: 9
    Last Post: 12-10-2009, 03:32 AM
  3. Command Colors
    By erik in forum Linux Applications
    Replies: 1
    Last Post: 08-07-2008, 05:52 AM
  4. Colors
    By NeedHelp in forum The Lounge
    Replies: 22
    Last Post: 07-11-2007, 09:49 PM
  5. Have you used colors?
    By Sir_Rimo in forum General Programming
    Replies: 2
    Last Post: 01-16-2007, 06:29 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts