Color Converter (HEX/RGB/HSL) — Developer Code Samples

Convert between HEX, RGB, HSL, and HSV color formats programmatically. Python's colorsys module and CSS Color Level 4 APIs handle most conversions. These patterns are useful for design systems, color palette generators, and image processing tools.

Try the interactive version online: Open Color Converter Tool →

Parameters

Parameter Type Required Description
color str Yes Input color in HEX (#RRGGBB), RGB (r,g,b), or HSL format
from_format str No Source format: hex, rgb, hsl, hsv (default: hex)
to_format str No Target format: hex, rgb, hsl, hsv (default: rgb)

Returns: Color value in target format as string (HEX) or tuple/dict (RGB, HSL)

Code Examples

import colorsys
import re

def hex_to_rgb(hex_color):
    """Convert HEX color (#RRGGBB) to RGB tuple."""
    hex_color = hex_color.lstrip('#')
    if len(hex_color) == 3:
        hex_color = ''.join(c * 2 for c in hex_color)
    r, g, b = int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
    return (r, g, b)

def rgb_to_hex(r, g, b):
    """Convert RGB values (0-255) to HEX string."""
    return f"#{r:02X}{g:02X}{b:02X}"

def rgb_to_hsl(r, g, b):
    """Convert RGB (0-255) to HSL (0-360, 0-100%, 0-100%)."""
    r_norm, g_norm, b_norm = r/255, g/255, b/255
    h, l, s = colorsys.rgb_to_hls(r_norm, g_norm, b_norm)
    return (round(h * 360), round(s * 100), round(l * 100))

def hsl_to_rgb(h, s, l):
    """Convert HSL (0-360, 0-100, 0-100) to RGB (0-255)."""
    h_norm = h / 360
    s_norm = s / 100
    l_norm = l / 100
    r, g, b = colorsys.hls_to_rgb(h_norm, l_norm, s_norm)
    return (round(r * 255), round(g * 255), round(b * 255))

def hex_to_hsl(hex_color):
    r, g, b = hex_to_rgb(hex_color)
    return rgb_to_hsl(r, g, b)

# Examples
print(hex_to_rgb("#FF5733"))      # (255, 87, 51)
print(rgb_to_hex(255, 87, 51))    # #FF5733
print(rgb_to_hsl(255, 87, 51))    # (11, 100, 60)
print(hsl_to_rgb(11, 100, 60))    # (255, 87, 51)
print(hex_to_hsl("#1E90FF"))      # (210, 100, 56)