How to convert hex to RGB and RGB to hex in Python

In this Answer, we are going to see how we can convert any hexadecimal color code value to its RGB format equivalent and vice-versa. Let’s see them one by one.

Converting hex to RGB

We will use the following approach to convert hex color codes into RGB format:

  • The RGB format has three values: Red, Green, and Blue.
  • Hex color codes have a length of 6, i.e., they can contain 6 hex values (like BAFD32, AAFF22, etc).
  • We need to take two hex values for one RGB value, convert those two hex values to decimal values, and then perform the same step with the other values.
  • We will get 3 values that correspond to RGB values.

Let’s see how this can be implemented in the code.

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('FFA501'))

Explanation

  • Line 1: We define the hex_to_rgb() function that accepts the hex color code values.
  • Line 3: We run the loop by taking two hex values from the color code at a time.
  • Line 4: We convert the two hex values to their decimal representation by specifying the base as 16 in the int() function.
  • Line 7: We return the result in tuple formatthe format in which RGB values are stored.

Now, let’s see how we can convert the RGB values to their hex representation.

Converting RGB to hex

To convert RGB values to hex values, we are going to take the three RGB values and convert them to their hex representation using :02x while returning the hex value.

Now, let’s take a look at the code.

def rgb_to_hex(r, g, b):
return '#{:02x}{:02x}{:02x}'.format(r, g, b)
print(rgb_to_hex(255, 165, 1))

Explanation

  • Line 1: A function named rgb_to_hex is defined with three arguments r, g, and b.

  • Line 2: The function returns a string in the format #RRGGBB where RR, GG, and BB are the hexadecimal representation of r, g, and b respectively. The format method is used to construct the string with :02x specifying that the values should be formatted as two-digit hexadecimal numbers with leading zeros added if necessary.

  • Line 4: The line print(rgb_to_hex(255, 165, 1)) calls the rgb_to_hex function with the arguments 255, 165, and 1 and prints the result #ffa501.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved