Created
August 1, 2019 14:32
-
-
Save fabioluzm/6774c699158b0601c0eced897f3b8d8f to your computer and use it in GitHub Desktop.
Convert HEX to RGB
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
<cffunction name="HexToRGB" returnType="string" hint="Convert HEX code to RGB(A) using 3 or 6 HEX digit value (valid examples: ##FFF, FFF, ##FFFFFF, FFFFFF)" access="remote"> | |
<!--- Variable that will receive the converted RGB value ---> | |
<cfset var rgbColor = ""> | |
<!--- Start out with a base HEX web color of 3 or 6 digit value. ---> | |
<cfset var HexColor = ARGUMENTS.HexColor> | |
<!--- look for a leading '#' and set an offset to use as a caller to removeChars ---> | |
<cfset var offset = 0> | |
<cfif Mid(HexColor, 1, 1) EQ chr(35)> | |
<cfset offset = 1> | |
</cfif> | |
<!--- Clean the code by removing any non-hex values ---> | |
<cfset var cnt = 0> | |
<cfloop from="#1 + offset#" to="#len(HexColor)#" index="i"> | |
<cfset currentHexColor = Mid(HexColor, i + cnt, 1)> | |
<cfif find(currentHexColor, '0123456789ABCDEFabcdef') EQ 0> | |
<cfset HexColor = removeChars(HexColor, i + cnt, 1)> | |
<cfset cnt = cnt - 1> | |
</cfif> | |
</cfloop> | |
<!--- Keep converting the HEX is value has 6 or 3 digits after the cleansing ---> | |
<cfif len(HexColor) EQ 6 OR len(HexColor) EQ 3> | |
<!--- Get the red, green, and blue parts (each one or two characters of the given HEX value) ---> | |
<!--- If HEX has 3 digits split and duplicate each value to create pairs---> | |
<cfif len(HexColor) EQ 3> | |
<cfset HexRed = Mid(HexColor, 1, 1) & Mid(HexColor, 1, 1)> | |
<cfset HexGreen = Mid(HexColor, 2, 1) & Mid(HexColor, 2, 1)> | |
<cfset HexBlue = Mid(HexColor, 3, 1) & Mid(HexColor, 3, 1)> | |
<!--- If HEX has 6 digits split into pairs ---> | |
<cfelseif len(HexColor) EQ 6> | |
<cfset HexRed = Mid(HexColor, 1, 2)> | |
<cfset HexGreen = Mid(HexColor, 3, 2)> | |
<cfset HexBlue = Mid(HexColor, 5, 2)> | |
</cfif> | |
<!--- | |
Convert the HEX colors to RGB decimal colors | |
where 0x00 = 00 and 0xFF = 255. HEX is base | |
16 and we want to convert to base 10 (our | |
standard number system). | |
---> | |
<cfset rgbRed = InputBaseN( HexRed, 16 )> | |
<cfset rgbGreen = InputBaseN( HexGreen, 16 )> | |
<cfset rgbBlue = InputBaseN( HexBlue, 16 )> | |
<!--- If opacity value is passed on arguments, add it to a RGBA value. Else keep the current RBG value ---> | |
<cfif StructKeyExists(ARGUMENTS, 'opacity')> | |
<cfset rgbColor = 'rgba(#rgbRed#,#rgbGreen#,#rgbBlue#,#ARGUMENTS.opacity#)'> | |
<cfelse> | |
<cfset rgbColor = 'rgb(#rgbRed#,#rgbGreen#,#rgbBlue#)'> | |
</cfif> | |
</cfif> | |
<!--- Return the converted value ---> | |
<cfreturn rgbColor> | |
</cffunction> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment