Last active
June 2, 2021 03:42
-
-
Save harish81/01491dd3cba0738f61aeb1597f4247d1 to your computer and use it in GitHub Desktop.
PHP function to convert hex color to RGB with alpha support
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
/** | |
* Convert the hex color to rgba. | |
* @param $hex - #fa11cc | |
* @param mixed $alpha - from 0.0 to 1.0 | |
* @return array rgba | |
*/ | |
function hexToRgb($hex, $alpha = false) | |
{ | |
$hex = str_replace('#', '', $hex); | |
$length = strlen($hex); | |
$rgb['red'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0)) / 255; | |
$rgb['green'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0)) / 255; | |
$rgb['blue'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0)) / 255; | |
if ($alpha) { | |
$rgb['alpha'] = $alpha; | |
} | |
return $rgb; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment