. Advertisement .
..3..
. Advertisement .
..4..
If you are searching for a method to convert HEX to RGB and vice versa, you hit the right place. This tutorial will show you how to convert HEX to RGB in Python.
Convert HEX To RGB in python
Both HEX and RGB are color codes which stand for different colors. RGB represents green, red, and blue. Each shows a unique value resulting in white color.
On the other hand, the HEX color codes are 6 long, for example, including six values.
To convert between these two color codes, you need to use a list comprehension with list slice notation and int() function. This way, you will get RGB components from the string.
Then, the tuple() function is used to convert this list to a tuple and offer the final result.
So let’s see how to convert HEX to RGB in python:
def hex_rgb(hex):
exp_rgb = []
for j in (0, 2, 4):
decimal = int(hex[j:j+2], 16)
exp_rgb.append(decimal)
return tuple(exp_rgb)
print(hex_rgb('FAEBD7'))
Output:
(250, 235, 215)
To explain the code, line 1 defines the hex_rgb() function. This function accepts the HEX code value. On the other hand, line 2 takes two HEX values at a time to run the loop.
Line 5 specifies the base in the int() function to convert two HEX values to decimal representations. After these steps, we return a result in a tuple format.
Method 1: Use PIL
Besides, you can also make use of the Python Image Library PIL to convert these two color codes:
Input:
from PIL import ImageColor
exp_hex = input('Please Enter the HEX value: ')
ImageColor.getcolor(exp_hex, "RGB")
Output:
Please Enter the HEX value: #FAEBD7
Method 2: Use Self-Defined Method
Input:
exp_hex1 = input('Please Enter the HEX value: ').lstrip('#')
print('The RGB value =', tuple(int(exp_hex1[i:i+2], 16) for i in (0, 2, 4)))
Output:
Please Enter the HEX value: #FAEBD7
The RGB value = (250, 235, 215)
How To Convert RGB To HEX in python
In this case, we will take three RGB values and convert to their HEX representation. The first step requires us to create a placeholder. This one stands for a zero-padded hexadecimal value named ‘{:02X}’.
Copy this value three times before using the str.format() on the resulting string.
Input:
def hex_rgb(R, G, B):
return ('{:X}{:X}{:X}').format(R, G, B)
print('#',hex_rgb(255, 250, 205))
Output:
# FFFACD
In the first line, the rgb_hex() function is defined to accept three given RGB values. Line 2 creates HEX values using the {:X} format to convert decimal values automatically to HEX ones.
The result in line 4 passes in the RGB values.
Conclusion
How to convert HEX to RGB in python? The tutorial has offered guidelines to convert any hexadecimal color code value to RGB format and vice versa.
Leave a comment