A UDT to convert HEX color to RGB

Do something cool with CMS? Show us ...
This board is for 'Answers', and the discussion of answers... Not for questions.
Locked
Simon66
Forum Members
Forum Members
Posts: 247
Joined: Wed Aug 29, 2007 4:36 am
Location: Sydney Australia

A UDT to convert HEX color to RGB

Post 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
User avatar
DIGI3
Dev Team Member
Dev Team Member
Posts: 1103
Joined: Wed Feb 25, 2009 4:25 am
Location: Victoria, BC

Re: A UDT to convert HEX color to RGB

Post by DIGI3 »

Nice! Have you tried calling it in a stylesheet too?
Not getting the answer you need? CMSMS support options
Simon66
Forum Members
Forum Members
Posts: 247
Joined: Wed Aug 29, 2007 4:36 am
Location: Sydney Australia

Re: A UDT to convert HEX color to RGB

Post 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
Simon66
Forum Members
Forum Members
Posts: 247
Joined: Wed Aug 29, 2007 4:36 am
Location: Sydney Australia

Re: A UDT to convert HEX color to RGB

Post 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) . ')';
Locked

Return to “Tips and Tricks”