I\'d like to convert a hex triplet to an RGB tuple and then convert a tuple to a hex triplet.
Here you go. I use it to convert color to graphviz color format in #RGBA
format with prefix=#
.
def rgba_hex( color, prefix = '0x' ):
if len( color ) == 3:
color = color + (255,)
hexColor = prefix + ''.join( [ '%02x' % x for x in color ] )
return hexColor
USAGE:
In [3]: rgba_hex( (222, 100, 34) )
Out[3]: '0xde6422ff'
In [4]: rgba_hex( (0,255,255) )
Out[4]: '0x00ffffff'
In [5]: rgba_hex( (0,255,255,0) )
Out[5]: '0x00ffff00'
I found a simple way:
red, green, blue = bytes.fromhex("aabbcc")
matplotlib uses RGB tuples with values between 0 and 1:
from matplotlib.colors import hex2color, rgb2hex
hex_color = '#00ff00'
rgb_color = hex2color(hex_color)
hex_color_again = rgb2hex(rgb_color)
both rgb_color
and hex_color
are in a format acceptable by matplotlib.
html uses RGB tuples with values between 0 and 255.
you can convert between them with the module webcolors, using the functions hex_to_rgb
, rgb_to_hex
def hex_to_int_color(v):
if v[0] == '#':
v = v[1:]
assert(len(v) == 6)
return int(v[:2], 16), int(v[2:4], 16), int(v[4:6], 16)
def int_to_hex_color(v):
assert(len(v) == 3)
return '#%02x%02x%02x' % v