Convert HEX to RGB in Python

Muhammad Maisam Abbas Oct 10, 2023
  1. Convert a Hexadecimal Value to an RGB Value With the Python Image Library PIL in Python
  2. Convert a Hexadecimal Value to an RGB Value With the Self-Defined Method in Python
Convert HEX to RGB in Python

This article introduces the methods you can use to convert a Hexadecimal value to an RGB value in Python.

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

The PIL library or Python Image Library provides many tools for working with images in Python. If we have a Hexadecimal value and we want to convert it to a corresponding RGB value, we can use the PIL library for that. The ImageColor.getcolor() function in the PIL library takes a color string and converts it to a corresponding RGB value. The following example program demonstrates how we can convert a Hexadecimal value to an RGB value with the PIL library.

from PIL import ImageColor

hex = input("Enter HEX value: ")
ImageColor.getcolor(hex, "RGB")

Output:

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

We converted the Hexadecimal value from the user input to an RGB value with the ImageColor.getcolor() function in the PIL library of Python. We first input the Hexadecimal value from the user and assign it to the hex variable. After that, we convert the data inside hex to its RGB value with the ImageColor.getcolor() function. In the end, we print the resultant RGB value.

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

We will manually convert the user input from a Hexadecimal format to an RGB value in this method. First, we can remove the # character from the user input and convert the hexadecimal values to base-10 integer values with the int() function for each alternating index. After that, we can group these converted values into an RGB tuple with the tuple() function. The example program below shows how we can convert a Hexadecimal value to an RGB value with the self-defined approach.

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

Output:

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

We converted the Hexadecimal value from the user input to an RGB value with the self-defined approach in Python. We used the int() function to convert the input values from Hexadecimal to decimal and the tuple() function to group these values together into the RGB format. In the end, we used the print() function to display the resultant RGB value on the console window.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article - Python Hex