Working off Jeremy\'s response here: Converting hex color to RGB and vice-versa I was able to get a python program to convert preset colour hex codes (example #B4FBB8), howe
As HEX codes can be like "#FFF"
, "#000"
, "#0F0"
or even "#ABC"
that only use three digits. These are just the shorthand version of writing a code, which are the three pairs of identical digits "#FFFFFF"
, "#000000"
, "#00FF00"
or "#AABBCC"
.
This function is made in such a way that it can work with both shorthands as well as the full length of HEX codes. Returns RGB values if the argument hsl = False
else return HSL values.
import re
def hex_to_rgb(hx, hsl=False):
"""Converts a HEX code into RGB or HSL.
Args:
hx (str): Takes both short as well as long HEX codes.
hsl (bool): Converts the given HEX code into HSL value if True.
Return:
Tuple of length 3 consisting of either int or float values."""
if re.compile(r'#[a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?$').match(hx):
div = 255.0 if hsl else 0
if len(hx) <= 4:
return tuple(int(hx[i]*2, 16) / div if div else
int(hx[i]*2, 16) for i in (1, 2, 3))
else:
return tuple(int(hx[i:i+2], 16) / div if div else
int(hx[i:i+2], 16) for i in (1, 3, 5))
else:
raise ValueError(f'"{hx}" is not a valid HEX code.')
Here are some IDLE outputs.
>>> hex_to_rgb('#FFB6C1')
>>> (255, 182, 193)
>>> hex_to_rgb('#ABC')
>>> (170, 187, 204)
>>> hex_to_rgb('#FFB6C1', hsl=True)
>>> (1.0, 0.7137254901960784, 0.7568627450980392)
>>> hex_to_rgb('#ABC', hsl=True)
>>> (0.6666666666666666, 0.7333333333333333, 0.8)
>>> hex_to_rgb('#00FFFF')
>>> (0, 255, 255)
>>> hex_to_rgb('#0FF')
>>> (0, 255, 255)