I am finding examples converting 8 digit hex colors into RGBA, but not the other way around.
Is there a PHP function that will convert RGBA color codes into 8 digit Hex? (The kind that start with "&H")
Something like:
$colorcode = 'rgba(123,100,23,.5);
$eightdigit = convertto8($colorcode);
Here is a function I put together based one of the answers, but I the last alpha channel is always coming out to zero:
function rgbtohex($string) {
$string = str_replace("rgba","",$string);
$string = str_replace("rgb","",$string);
$string = str_replace("(","",$string);
$string = str_replace(")","",$string);
$colorexplode = explode(",",$string);
$hex = '&H';
foreach($colorexplode AS $c) {
echo "C" . $c . " " . dechex($c) . "<br><br>";
$hex .= dechex($c);
}
return $hex;
}
Then if I test it:
$rgb = 'rgba(123,223,215,.9)';
$rgb = rgbtohex($rgb);
echo $rgb;
This produces the following:
&H7bdfd70 which only has 7 characters instead of 8.
Also, the alpha channel (.9) always comes out to zero, so that doesn't appear to be working correctly.
CodePudding user response:
You can use the dechex() function to convert each param of your rgba color to a 2 hex digit.
So in your example you have to concat each part of the rgba to get the hex value of your color :
dechex(123).dechex(100).dechex(23).dechex(0.5)
CodePudding user response:
You can use the printf()
family of functions to convert to a properly padded hex string. Decimals cannot be represented in hex, so the value is taken as a fraction of 0xFF.
$rgba = "rgba(123,100,23,.5)";
// get the values
preg_match_all("/([\\d.] )/", $rgba, $matches);
// adjust opacity
$matches[1][3] *= 255;
// output
$hex = vsprintf("&HXXXX", $matches[1]);
echo $hex;
Output:
&H7B64177F