Last active
June 17, 2022 09:22
-
-
Save clemblanco/adb73dae3dc5308553f9 to your computer and use it in GitHub Desktop.
Convert RGBA into HEXADECIMAL or HEXADECIMAL into RGBA with transparency support.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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