Page 1 of 1

A UDT to convert HEX color to RGB

Posted: Thu Apr 11, 2019 12:27 am
by Simon66
UDT titled hex2rgb:

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']);
And the call to it:

Code: Select all

{hex2rgb hex='#28a745' alpha=0.5}
or
{hex2rgb hex='#28a745'}
And the output:

Code: Select all

rgba(40, 167, 69, 0.5)
or
rgb(40, 167, 69)
Works with 3 digit and 6 digit HEX colors.
Works with or without ALPHA channel.
Hope it's useful to someone.

Cheers
Simon66

Re: A UDT to convert HEX color to RGB

Posted: Thu Apr 11, 2019 2:55 am
by DIGI3
Nice! Have you tried calling it in a stylesheet too?

Re: A UDT to convert HEX color to RGB

Posted: Thu Apr 11, 2019 4:58 am
by Simon66
I hadn't thought of it.
I came up with this UDT so I could to use the colorpicker in Custom Global Settings (CustomGS) for changing the color of the 'filter_colorize="r,g,b[,alpha]"' in CGSmartImage.

I've created a section where an Editor can upload & custom colorize a photo.

I'll play around with it and see what else it can do.

Cheers
Simon66

Re: A UDT to convert HEX color to RGB

Posted: Fri Apr 12, 2019 11:42 pm
by Simon66
Thanks to Jo Morg it's been updated to use multiple times on a page.

Code: Select all

 $hex = $params['hex'];
 $alpha = $params['alpha'];
   $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;
   }
   echo implode(array_keys($rgb)) . '(' . implode(', ', $rgb) . ')';