Converting colors between hex #RRGGBB and rgb()/rgba() using Velocity

As if the rules for HTML email weren’t complex enough, sometimes the exact same color needs to be represented in 2 different ways for different mail clients.

Rather than having 2 different variables for #A1B2C3 and rgba(161,178,195,.5) and remembering to keep them exactly in sync, you can populate just one and seamlessly convert it to the other using Velocity.

Here are two Velocimacros, #hexToRGB_v1 and #rgbToHex_v1:

#macro( hexToRGB_v1 $hexColor $opacity)
#set( $Integer = 0 )
#set( $hexValues = $hexColor.replaceAll("[${esc.h} ]","").split("(?<=\G..)") )
#set( $intValues = [] )
#foreach( $color in $hexValues )
#set( $void = $intValues.add( $Integer.parseInt($color,16) ) )
#end
#if( !$opacity )
#set( $rgb = "rgb(" + $display.list($intValues,",") + ")" )
${rgb}##
#else
#set( $rgba = "rgba(" + $display.list($intValues,",") + "," + $opacity + ")" )
${rgba}##
#end
#end
#macro( rgbToHex_v1 $rgbColor )
#set( $intValues = $rgbaColor.replaceAll("(?i)[rgba() ]","").split(",") )
#set( $hexValues = [] )
#foreach( $color in $intValues )
#if( $foreach.index > 2 )#break#end
#set( $void = $hexValues.add( $display.printf("%02X",$convert.toNumber($color).intValue()) ) )
#end
#set( $hex = $esc.h + $display.list($hexValues,"") )
${hex}##
#end

Usage:

#set( $hexColor= ${esc.h} + "A1B2C3" )
#hexToRGB_v1( $hexColor ) ## prints rgb(161,178,195)

#set( $hexColor= ${esc.h} + "A1B2C3" )
#hexToRGB_v1( $hexColor ".5" ) ## prints rgba(161,178,195,.5)

#set( $rgbaColor = "rgba(161,178,195)" )
#rgbToHex_v1( $rgbaColor ) ## prints #A1B2C3

Both macros expect valid input (that is, if you accidentally pass %A!B^@3 instead of #A1B2C3, that’s on you!).

And #rgbToHex_v1 accepts either rgb() or rgba() as input, though it only outputs #RRGGBB (support for #RRGGBBAA is nonexistent in email anyway).

Enjoy!