Converting hex color to RGB and vice-versa

In python:

def hex_to_rgb(value):
    """Return (red, green, blue) for the color given as #rrggbb."""
    value = value.lstrip('#')
    lv = len(value)
    return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))

def rgb_to_hex(red, green, blue):
    """Return color as #rrggbb for the given color values."""
    return '#%02x%02x%02x' % (red, green, blue)

hex_to_rgb("#ffffff")           #==> (255, 255, 255)
hex_to_rgb("#ffffffffffff")     #==> (65535, 65535, 65535)
rgb_to_hex(255, 255, 255)       #==> '#ffffff'
rgb_to_hex(65535, 65535, 65535) #==> '#ffffffffffff'

In python conversion between hex and 'rgb' is also included in the plotting package matplotlib. Namely

import matplotlib.colors as colors

Then

colors.hex2color('#ffffff')        #==> (1.0, 1.0, 1.0)
colors.rgb2hex((1.0, 1.0, 1.0))    #==> '#ffffff'

The caveat is that rgb values in colors are assumed to be between 0.0 and 1.0. If you want to go between 0 and 255 you need to do a small conversion. Specifically,

def hex_to_rgb(hex_string):
    rgb = colors.hex2color(hex_string)
    return tuple([int(255*x) for x in rgb])

def rgb_to_hex(rgb_tuple):
    return colors.rgb2hex([1.0*x/255 for x in rgb_tuple])

The other note is that colors.hex2color only accepts valid hex color strings.

Tags:

Hex

Colors

Rgb