A UDT to convert HEX color to RGB
Posted: Thu Apr 11, 2019 12:27 am
UDT titled hex2rgb:
And the call to it:
And the output:
Works with 3 digit and 6 digit HEX colors.
Works with or without ALPHA channel.
Hope it's useful to someone.
Cheers
Simon66
Code: Select all
function hex2rgb($hex, $alpha = false) {
$hex = str_replace('#', '', $hex);
$length = strlen($hex);
$rgb['r'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0));
$rgb['g'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0));
$rgb['b'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0));
if ( $alpha ) {
$rgb['a'] = $alpha;
}
return implode(array_keys($rgb)) . '(' . implode(', ', $rgb) . ')';
}
echo hex2rgb($params['hex'], $params['alpha']);
Code: Select all
{hex2rgb hex='#28a745' alpha=0.5}
or
{hex2rgb hex='#28a745'}
Code: Select all
rgba(40, 167, 69, 0.5)
or
rgb(40, 167, 69)
Works with or without ALPHA channel.
Hope it's useful to someone.
Cheers
Simon66