Skip to content

Instantly share code, notes, and snippets.

@clemblanco
Last active June 17, 2022 09:22
Show Gist options
  • Save clemblanco/adb73dae3dc5308553f9 to your computer and use it in GitHub Desktop.
Save clemblanco/adb73dae3dc5308553f9 to your computer and use it in GitHub Desktop.
Convert RGBA into HEXADECIMAL or HEXADECIMAL into RGBA with transparency support.
<?php
function hex2rgba($hex) {
$hex = str_replace("#", "", $hex);
switch (strlen($hex)) {
case 3 :
$r = hexdec(substr($hex, 0, 1).substr($hex, 0, 1));
$g = hexdec(substr($hex, 1, 1).substr($hex, 1, 1));
$b = hexdec(substr($hex, 2, 1).substr($hex, 2, 1));
$a = 1;
break;
case 6 :
$r = hexdec(substr($hex, 0, 2));
$g = hexdec(substr($hex, 2, 2));
$b = hexdec(substr($hex, 4, 2));
$a = 1;
break;
case 8 :
$a = hexdec(substr($hex, 0, 2)) / 255;
$r = hexdec(substr($hex, 2, 2));
$g = hexdec(substr($hex, 4, 2));
$b = hexdec(substr($hex, 6, 2));
break;
}
$rgba = array($r, $g, $b, $a);
return 'rgba('.implode(', ', $rgba).')';
}
function rgba2hex($string) {
$rgba = array();
$hex = '';
$regex = '#\((([^()]+|(?R))*)\)#';
if (preg_match_all($regex, $string ,$matches)) {
$rgba = explode(',', implode(' ', $matches[1]));
} else {
$rgba = explode(',', $string);
}
$rr = dechex($rgba['0']);
$gg = dechex($rgba['1']);
$bb = dechex($rgba['2']);
$aa = '';
if (array_key_exists('3', $rgba)) {
$aa = dechex($rgba['3'] * 255);
}
return strtoupper("#$aa$rr$gg$bb");
}
echo 'rgba(175, 175, 175) --> ' . rgba2hex('rgba(175, 175, 175)') . '<br />';
echo 'rgba(175, 175, 175, 0.80) --> ' . rgba2hex('rgba(175, 175, 175, 0.80)') . '<br />';
echo '#CCAFAFAF --> ' . hex2rgba('#CCAFAFAF').'<br />';
echo '#AFAFAF --> ' . hex2rgba('#AFAFAF');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment