[reportlab-users] HexColor()

Lalo Martins reportlab-users@reportlab.com
Mon, 17 Feb 2003 18:01:34 -0300


Ok, this is broken :-) Magnus pointed out that the current implementation
divides by 256 and not 0x100, I must have lost something in the zigzagging
between hex and decimal.  The *correct* function is below:

def HexColor(val):
	"""This function converts a hex string into the corresponding
	color.  E.g., in "AABBCC" or 0xAABBCC, AA is the red, BB is
	the green, and CC is the blue (00-FF).  In "AABBCCDD", AA is
	cyan, BB is magenta, CC yellow, DD black.
	
	You can use any "depth" you want, ABC == AABBCC == AAABBBCCC

	HTML uses a hex string with a preceding hash; if this is present,
	it is stripped off.  (AR, 3-3-2000)
	"""

        if val[:1] == '#':
            val = val[1:]
        elif val[:2].lower() == '0x':
            val = val[2:]
        l = len(val)
        if (l%4) == 0:
            # cmyk
            w = l/4
            c = int(val[:w], 0x10)
            m = int(val[w:w*2], 0x10)
            y = int(val[w*2:w*3], 0x10)
            k = int(val[w*3:], 0x10)
            scale = float(0x10 ** w) - 1
            return colors.CMYKColor(c/scale, m/scale, y/scale, k/scale)
        if (l%3) == 0:
            # rgb
            w = l/3
            r = int(val[:w], 0x10)
            g = int(val[w:w*2], 0x10)
            b = int(val[w*2:], 0x10)
            scale = float(0x10 ** w) - 1
            return colors.Color(r/scale, g/scale, b/scale)
        raise ValueError, "unknown hex color format"

this code is hereby donated to the public domain.


[]s,
                                               |alo
                                               +----
--
            Those who trade freedom for security
               lose both and deserve neither.
--
http://www.laranja.org/                mailto:lalo@laranja.org
         pgp key: http://www.laranja.org/pessoal/pgp

Eu jogo RPG! (I play RPG)         http://www.eujogorpg.com.br/
GNU: never give up freedom                 http://www.gnu.org/