Converting Hex to RGB value in Python

123,900

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")]
Share:
123,900

Related videos on Youtube

Julian White
Author by

Julian White

Management major, IT & Entrepreneurship minor (uni student)

Updated on April 27, 2022

Comments

  • Julian White
    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.

  • koukouviou
    koukouviou about 9 years
    It is better to avoid overriding hex. Maybe something like hex_in or similar is better
  • Julian White
    Julian White about 9 years
    Good point, @koukouviou - Python reports it as built-in name.
  • Julian White
    Julian White about 9 years
    Beautiful. Cuts 23 lines down to two, only suggestion is fixing to for i in (0, 2, 4)))
  • Julian White
    Julian White about 9 years
    Question, 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
    John1024 about 9 years
    @JulianWhite No problem. I updated the answer using string formatting suitable for f.write.
  • Gürol Canbek
    Gürol Canbek almost 7 years
    By 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
    Typewar over 5 years
    This was apparently the only solution that worked for me.
  • Typewar
    Typewar over 5 years
    Getting error "TypeError: 'float' object cannot be interpreted as an integer"
  • John1024
    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
    bugmenot123 over 4 years
    Well the question was about hex.
  • MathanKumar
    MathanKumar about 4 years
    Hey @SuperNova how to get the name of color instead of pixel values?
  • SuperNova
    SuperNova about 4 years
    hwy @Mvk1312. Please check this. stackoverflow.com/questions/9694165/…
  • Ideogram
    Ideogram about 4 years
    It 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
    Ideogram about 4 years
    In case you need values from 0…1: rgb = [i/256 for i in (ImageColor.getrgb("#9b9b9b"))]
  • ilykos
    ilykos almost 3 years
    I 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
    WinEunuuchs2Unix almost 3 years
    Although 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
    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 with from __future__ import print_function
  • WinEunuuchs2Unix
    WinEunuuchs2Unix almost 3 years
    @John1024 Gotcha. When I started out with 2.7.12 I was using print from the future I forgot all about that problem for others.
  • Barış Şenyerli
    Barış Şenyerli over 2 years
    I found this solution is fastest one.