Convert Color code from HEX to RGB using PHP

Convert Color code from HEX to RGB using PHP

Today I am going to show an useful function that converts HEX to RGB of a color . Often we used directly the name of a color like “red”,”green”,”yellow” and sometimes we preferred to use the HEX code of a color like “#FFFFFF” for white or “#0000000” for black. However, If you want to use opacity property for text-shadow or box shadow, then you need to use the RGB color code instead of direct or HEX color code.

Yesterday, I was working on a client project where I needed to convert HEX to RGB of a color. Here goes PHP snippet that I had used into my project.

– Convert Color Code From RGB To HEX:

function HexToRGB($hex) {
    $hex = ereg_replace("#", "", $hex);
    $color = array();

    if (strlen($hex) == 3) {
        $color['r'] = hexdec(substr($hex, 0, 1) . $r);
        $color['g'] = hexdec(substr($hex, 1, 1) . $g);
        $color['b'] = hexdec(substr($hex, 2, 1) . $b);
    } else if (strlen($hex) == 6) {
        $color['r'] = hexdec(substr($hex, 0, 2));
        $color['g'] = hexdec(substr($hex, 2, 2));
        $color['b'] = hexdec(substr($hex, 4, 2));
    }

    return $color;
}

– Convert Color Code From RGB To HEX:

function RGBToHex($r, $g, $b) {    
    $hex = "#";
    $hex.= str_pad(dechex($r), 2, "0", STR_PAD_LEFT);
    $hex.= str_pad(dechex($g), 2, "0", STR_PAD_LEFT);
    $hex.= str_pad(dechex($b), 2, "0", STR_PAD_LEFT);
    return $hex;
}

Enjoy!

Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!

Total 0 Votes
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Comment

Back To Top