Last active
January 10, 2020 08:16
-
-
Save cesurapp/78251b309fdd36520830fd3cecc802d6 to your computer and use it in GitHub Desktop.
PHP Hex to RGBA
This file contains 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 | |
/** | |
* Hex to RGBA | |
* | |
* @param string $hexColor | |
* @param string|int|double $opacity | |
* | |
* @return string | |
*/ | |
function hexToRgba(string $hexColor, $opacity = 1): string | |
{ | |
// Remove # Chacter | |
if ($hexColor[0] === '#'){ | |
$hexColor = substr($hexColor, 1); | |
} | |
// Convert to Array | |
if (strlen($hexColor) === 3) { | |
$hexColor = str_split($hexColor); | |
foreach ($hexColor as $index => $color) { | |
$hexColor[$index] = $color . $color; | |
} | |
} else if (strlen($hexColor) === 6){ | |
$hexColor = str_split($hexColor, 2); | |
} else { | |
throw new Exception('Invalid Hex Color'); | |
} | |
// Result to RGBA | |
return sprintf('rgba(%s, %s)', implode(',', array_map('hexdec', $hexColor)), $opacity); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
hexToRgba('#AABBCC', 0.2)