Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Hex to RGB value in Python

Tags:

python

colors

rgb

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), however from an end-user perspective we can't ask people to edit code & run from there. How can one prompt the user to enter a hex value and then have it spit out a RGB value from there?

Here's the code I have thus far:

def hex_to_rgb(value):     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(rgb):     return '#%02x%02x%02x' % rgb  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'  print('Please enter your colour hex')  hex == input("")  print('Calculating...') print(hex_to_rgb(hex())) 

Using the line print(hex_to_rgb('#B4FBB8')) I'm able to get it to spit out the correct RGB value which is (180, 251, 184)

It's probably super simple - I'm still pretty rough with Python.

like image 468
Julian White Avatar asked Apr 15 '15 06:04

Julian White


People also ask

How do you convert hexadecimal to Python?

When denoting hexadecimal numbers in Python, prefix the numbers with '0x'. Also, use the hex() function to convert values to hexadecimal format for display purposes.


2 Answers

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) 

Writing to a file

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)) )) 
like image 93
John1024 Avatar answered Oct 21 '22 15:10

John1024


You can use ImageColor from Pillow.

>>> from PIL import ImageColor >>> ImageColor.getcolor("#23a9dd", "RGB") (35, 169, 221) 
like image 39
SuperNova Avatar answered Oct 21 '22 15:10

SuperNova