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
The following function will convert hex string to rgb values:
def hex_to_rgb(hex_string):
r_hex = hex_string[1:3]
g_hex = hex_string[3:5]
b_hex = hex_string[5:7]
return int(r_hex, 16), int(g_hex, 16), int(b_hex, 16)
This will convert the hexadecimal_string to decimal number
int(hex_string, 16)
For example:
int('ff', 16) # Gives 255 in integer data type
I believe that this does what you are looking for:
h = input('Enter hex: ').lstrip('#')
print('RGB =', tuple(int(h[i:i+2], 16) for i in (0, 2, 4)))
(The above was written for Python 3)
Sample run:
Enter hex: #B4FBB8
RGB = (180, 251, 184)
To write to a file with handle fhandle
while preserving the formatting:
fhandle.write('RGB = {}'.format( tuple(int(h[i:i+2], 16) for i in (0, 2, 4)) ))
A lazy option:
webcolors package has a hex_to_rgb
function.
PIL also has this function, in ImageColor.
from PIL import ImageColor
ImageColor.getrgb("#9b9b9b")
And if you want the numbers from 0 to 1
[i/256 for i in ImageColor.getrgb("#9b9b9b")]
You can use ImageColor
from Pillow.
>>> from PIL import ImageColor
>>> ImageColor.getcolor("#23a9dd", "RGB")
(35, 169, 221)
All the answers I've seen involve manipulation of a hex string. In my view, I'd prefer to work with encoded integers and RGB triples themselves, not just strings. This has the benefit of not requiring that a color be represented in hexadecimal-- it could be in octal, binary, decimal, what have you.
Converting an RGB triple to an integer is easy.
rgb = (0xc4, 0xfb, 0xa1) # (196, 251, 161)
def rgb2int(r,g,b):
return (256**2)*r + 256*g + b
c = rgb2int(*rgb) # 12909473
print(hex(c)) # '0xc4fba1'
We need a little more math for the opposite direction. I've lifted the following from my answer to a similar Math exchange question.
c = 0xc4fba1
def int2rgb(n):
b = n % 256
g = int( ((n-b)/256) % 256 ) # always an integer
r = int( ((n-b)/256**2) - g/256 ) # ditto
return (r,g,b)
print(tuple(map(hex, int2rgb(c)))) # ('0xc4', '0xfb', '0xa1')
With this approach, you can convert to and from strings with ease.