Loading....

Convert Color code from HEX to RGB using PHP

Convert Color code from HEX to RGB using PHP

Hello friends, today I’m going to show you a cool function to convert color code from HEX to RGB. Well, most of the time we use directly color text like “red”,”green”,”yellow” and sometimes we uses color HEX code like “#FFFFFF” for white or “#0000000” for black. But If you want to use opacity property for text-shadow or box shadow then you need to use RGB code instead of direct or HEX color code. Last day working in a project and need to convert color code from HEX to RGB. Here goes snippet-

– 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!

Back To Top