Converting Hex to RGB value in Python
Solution 1
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)) ))
Solution 2
You can use ImageColor
from Pillow.
>>> from PIL import ImageColor
>>> ImageColor.getcolor("#23a9dd", "RGB")
(35, 169, 221)
Solution 3
Just another option: matplotlib.colors module.
Quite simple:
>>> import matplotlib.colors
>>> matplotlib.colors.to_rgb('#B4FBB8')
(0.7058823529411765, 0.984313725490196, 0.7215686274509804)
Note that the input of to_rgb
need not to be hexadecimal color format, it admits several color formats.
You can also use the deprecated hex2color
>>> matplotlib.colors.hex2color('#B4FBB8')
(0.7058823529411765, 0.984313725490196, 0.7215686274509804)
The bonus is that we have the inverse function, to_hex
and few extra functions such as, rgb_to_hsv
.
Solution 4
A lazy option:
webcolors package has a hex_to_rgb
function.
Solution 5
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")]
Related videos on Youtube
Julian White
Management major, IT & Entrepreneurship minor (uni student)
Updated on April 27, 2022Comments
-
Julian White about 2 years
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.
-
User over 5 yearspossible duplicate: stackoverflow.com/questions/5661725/…
-
-
koukouviou about 9 yearsIt is better to avoid overriding
hex
. Maybe something likehex_in
or similar is better -
Julian White about 9 yearsGood point, @koukouviou - Python reports it as built-in name.
-
Julian White about 9 yearsBeautiful. Cuts 23 lines down to two, only suggestion is fixing to
for i in (0, 2, 4)))
-
Julian White about 9 yearsQuestion, John1024, I'm writing the result (example #FFFFFF being (255, 255, 255)) to a file using f.write, it requests it be a string rather than a tuple. Is there any way I can convert it to a string preserving the commas and spaces? Cheers :)
-
John1024 about 9 years@JulianWhite No problem. I updated the answer using string formatting suitable for
f.write
. -
Gürol Canbek almost 7 yearsBy the way, currently webcolors does not have a
hex_to_rgb
where the tuples are specified in decimal value in range 0 and 1 (say hex_to_rgb_decimal). But, you can use this code that imports numpy and webcolors:tuple(numpy.array(webcolors.hex_to_rgb('#9C0006'))/255.0)
-
Typewar over 5 yearsThis was apparently the only solution that worked for me.
-
Typewar over 5 yearsGetting error "TypeError: 'float' object cannot be interpreted as an integer"
-
John1024 over 5 years@Typewar Are you using python3? (This code would have to be modified if you needed to use it with the soon-to-be-obsolete python2.) What exactly did you enter in response to the prompt? What is the full and complete error message that you see?
-
bugmenot123 over 4 yearsWell the question was about hex.
-
MathanKumar about 4 yearsHey @SuperNova how to get the name of color instead of pixel values?
-
SuperNova about 4 yearshwy @Mvk1312. Please check this. stackoverflow.com/questions/9694165/…
-
Ideogram about 4 yearsIt does not answer the question, but it gives insight into how it's done conceptually, so +1. (teach a man how to fish and so on... )
-
Ideogram about 4 yearsIn case you need values from 0…1: rgb = [i/256 for i in (ImageColor.getrgb("#9b9b9b"))]
-
ilykos almost 3 yearsI believe the last comment to be wrong. 255/256=0.99609. The values returned from
ImageColor.getrbb
are [0 ... 255], hard bounded by 255 upper limit. By dividing 256 you will never reach 1.0. Unless I am very wrong here, I suggest you change this to i/255. -
WinEunuuchs2Unix almost 3 yearsAlthough implied it doesn't, this works in Python 2.7.12 as well. Just remember to
.lstrip('#')
the tkinter color coded being passed to your function. -
John1024 almost 3 years@WinEunuuchs2Unix I get your point but to obtain the same screen output from py2, one should either change the print command to
print 'RGB =', tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
or else precede the print command withfrom __future__ import print_function
-
WinEunuuchs2Unix almost 3 years@John1024 Gotcha. When I started out with
2.7.12
I was usingprint
from the future I forgot all about that problem for others. -
Barış Şenyerli over 2 yearsI found this solution is fastest one.