Posted inPython

hex to rgb – How to convert hex to RGB and RGB to hex in Python?

hex to rgb – Conversion of RGB to hex and vice-versa in Python like RGB to Hex, Hex to RGB Example.

Convert HEX to RGB in Python

Converting Hex to RGB value in Python here we can learn to simple step by step Convert hex color to rgb Example. Best Practice to Python Convert Hex Color to RGB – Python Tutorial

value: [#]hex, such as #ff6600 or ff6600

return: [r, g, b]

Python Image Library PIL in Python

Example
Convert a Hexadecimal Value to an RGB Value With the Python Image Library PIL in Python

from PIL import ImageColor
hex = input('Please Enter HEX value: ')
ImageColor.getcolor(hex, "RGB")

Result

Please Enter HEX value: #B12345
Genrate RGB value = (177, 35, 69)

Self-Defined Method in Python

Convert a Hexadecimal Value to an RGB Value With the Self-Defined Method in Python
Example

hex = input('Please Enter HEX value: ').lstrip('#')
print('Genrate RGB value =', tuple(int(hex[i:i+2], 16) for i in (0, 2, 4)))

Result

Please Enter HEX value: #B12345
Genrate RGB value = (177, 35, 69)

Also Read : Black transparent color code

Conversion of RGB to hex and vice-versa in Python

Converting RGB to hex

def rgb_to_hex(r, g, b):
  return ('{:X}{:X}{:X}').format(r, g, b)

print(rgb_to_hex(255, 165, 1))

Converting hex to RGB

def hex_to_rgb(hex):
  rgb = []
  for i in (0, 2, 4):
    decimal = int(hex[i:i+2], 16)
    rgb.append(decimal)
  
  return tuple(rgb)

print(hex_to_rgb('ff0066'))

convert hex color to rgb python

hex_color = input('Enter hex: ').lstrip('#')
print('YOUR RGB COLOR IS=', tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4)))

hex to rgb python

from colormap import rgb2hex
from colormap import hex2rgb

print(rgb2hex(255, 255, 255))
print(hex2rgb('#FFFFFF'))

>>> #FFFFFF
>>> (255, 255, 255)

How to use?

hex_color = '#FFA501'
print(hex_to_rgb(hex_color))
hex_color = 'FFA501'
print(hex_to_rgb(hex_color))

I hope you get an idea about hex to rgb.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

I am Jaydeep Gondaliya , a software engineer, the founder and the person running Pakainfo. I'm a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, JavaScript, jQuery, Laravel, CodeIgniter, VueJS, AngularJS and Bootstrap from the early stage.

Leave a Reply

Your email address will not be published. Required fields are marked *

We accept paid guest Posting on our Site : Guest Post Chat with Us On Skype