Views: 8
RGB to HEX converter using python:
1.Function Definition:
-
- The rgb_to_hex function takes three parameters: r,g, and b, which are the red, green, and blue components of the color, respectively.
- The function checks if each component is within the valid range of 0 to 255. If not, it raises a value error
- Conversion to HEX:
- The function uses Python’s string formatting to convert each RGB component to a two-digit hexadecimal value. The {:02x} format specifier ensures that each value is represented as a two-digit uppercase hexadecimal number.
- The formatted string is prefixed with # to form the HEX color code.
- Example Usage:
- An example RGB color (255, 166,0) (which is orange) is converted to its HEX equivalent.
- The try-except block catches and prints any valueerror that might be raised due to invalid RGB values.
This script can be used as a module in larger projects or as a standalone tool for converting RGB values to HEX color codes.
Program:
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’))
def rgb_to_hex(r, g, b):
return ‘#{:02x}{:02x}{:02x}’.format(r, g, b)
print(rgb_to_hex(255, 165, 1))