HEX to RGBA String Conversion
Convert an hexadecimal colour value (e.g. from color chooser field) to RGB. Add an opacity parameter to receive an RGBA string.
Description
This utility may be passed an hexadecimal string such as #485EBC
and it will return the RGB equivalent (in this case, 72, 94, 188
). You may pass an opacity parameter to receive an RGBA string.
Hex values may be supplied both with or without leading # and the utility accepts both lower and upper case.
After importing this template into an xsl stylesheet, you would call the hex-to-rgba template like this:
<xsl:call-template name="rbga-to-hex"/>
<xsl:with-param name="hex-val" select="#485EBC"/>
</xsl:call-template>
This would output: 72, 94, 188
.
Or, for an RGBA string, call the template this way:
<xsl:call-template name="rbga-to-hex">
<xsl:with-param name="hex-val" select="#485EBC"/>
<xsl:with-param name="opacity" select="0.8"/>
</xsl:call-template>
It would output 72, 94, 188, 0.8
.
XSLT
View Raw
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template name="hex-to-rgba"> <xsl:param name="hex-val"/> <xsl:param name="opacity"/> <xsl:param name="hex" select="translate(translate($hex-val, '#', ''), 'abcdef', 'ABCDEF')"/> <xsl:variable name="r"> <xsl:call-template name="hexpairs-to-dec"> <xsl:with-param name="pair" select="1"/> <xsl:with-param name="hex" select="$hex"/> </xsl:call-template> </xsl:variable> <xsl:variable name="g"> <xsl:call-template name="hexpairs-to-dec"> <xsl:with-param name="pair" select="2"/> <xsl:with-param name="hex" select="$hex"/> </xsl:call-template> </xsl:variable> <xsl:variable name="b"> <xsl:call-template name="hexpairs-to-dec"> <xsl:with-param name="pair" select="3"/> <xsl:with-param name="hex" select="$hex"/> </xsl:call-template> </xsl:variable> <xsl:choose> <xsl:when test="string-length($opacity) > 0"> <xsl:value-of select="concat($r, ', ', $g, ', ', $b, ', ', $opacity)"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="concat($r, ', ', $g, ', ', $b)"/> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name="hexpairs-to-dec"> <xsl:param name="pair" select="1"/> <xsl:param name="hex"/> <xsl:variable name="hex-pair" select="substring($hex,$pair * 2 - 1,2)"/> <xsl:if test="$hex-pair"> <xsl:variable name="hex" select="'0123456789ABCDEF'"/> <xsl:value-of select="(string-length(substring-before($hex, substring($hex-pair,1,1))))*16 + string-length(substring-before($hex,substring($hex-pair,2,1)))"/> </xsl:if> </xsl:template> </xsl:stylesheet>