How convert rgba to hex6 color code in php?

Member

by deron , in category: PHP General , 5 months ago

How convert rgba to hex6 color code in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , 5 months ago

@deron 

You can convert an RGBA color code to a HEX6 color code in PHP using the following function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function rgba2hex6($rgba) {
    $rgba = str_replace('rgba(', '', $rgba);
    $rgba = str_replace(')', '', $rgba);
    $rgba = explode(',', $rgba);

    $r = intval($rgba[0]);
    $g = intval($rgba[1]);
    $b = intval($rgba[2]);

    $hex = "#".str_pad(dechex($r), 2, '0', STR_PAD_LEFT).str_pad(dechex($g), 2, '0', STR_PAD_LEFT).str_pad(dechex($b), 2, '0', STR_PAD_LEFT);

    return $hex;
}

$rgba = 'rgba(255, 0, 0)';
$hex = rgba2hex6($rgba);
echo $hex; // Output: #ff0000


This function first removes the 'rgba(' and ')' characters from the input string and splits the string into an array containing the RGB values. It then converts the RGB values to their decimal equivalents and converts them to HEX values using the dechex function. Finally, it concatenates the HEX values into a single string with a '#' prefix and returns the resulting HEX color code.