Color utilities
This module provides various utility functions for color conversion, manipulation, and random color generation.
hexStr
Converts an integer (0-255) to a two-digit hexadecimal string.
Parameters
- n(int): An integer value between 0 and 255.
random_int
Returns a random integer N such that min_val <= N <= max_val.
Parameters
- min_val(int): The minimum value.
- max_val(int): The maximum value.
str2rgb
Converts a hex color string to an RGB dictionary. Accepts strings in the format "#RRGGBB" or "#RGB".
If the input doesn't match, returns {'r': 0, 'g': 0, 'b': 0}.
Parameters
- col(str): A hex color string.
print(str2rgb("#ff0000"))  # Output: {'r': 255, 'g': 0, 'b': 0}
print(str2rgb("#f00"))     # Output: {'r': 255, 'g': 0, 'b': 0}
hex_to_rgb
Converts a hex color string (e.g., "#ff0000") to an (R, G, B) tuple.
Parameters
- hex_color(str): A hex color string in the format "#RRGGBB".
rgb_to_hex
Converts an (R, G, B) tuple to a hex color string.
Parameters
- rgb(tuple[int, int, int]): A tuple representing red, green, and blue values.
color2rgba
Converts an input color (which can be a list/tuple of three numbers, an integer, or a hex string) and an alpha value to an "rgba(r, g, b, a)" string.
Parameters
- c(list/tuple/int/str): The input color in one of the supported formats.
- alpha(float, optional): The alpha value (default is 1).
print(color2rgba((255, 0, 0), 0.5))   # Output: "rgba(255, 0, 0, 0.5)"
print(color2rgba("#00ff00", 0.75))     # Output: "rgba(0, 255, 0, 0.75)"
blend
Blends two hex color strings by the given proportion. A proportion of 0 returns color1 and 1 returns color2. Returns the blended color as a hex string.
Parameters
- color1(str): The first hex color string.
- color2(str): The second hex color string.
- proportion(float): The blend proportion (between 0 and 1).
random_color
Generates a random hex color string.
generate_colors
Generates a list of colors equally distributed on the color wheel. The function uses the hue of the provided base color as a starting point and preserves its lightness and saturation, then rotates the hue in equal increments to produce a balanced palette of n colors.
Parameters
- base_color(str): The starting color in hex format (e.g., "#db45f9"). This color provides the lightness and saturation for the generated palette.
- n(int): The total number of colors to generate.
Returns
- (list[str]): A list of hex color strings representing the generated color palette.
# Example: Generate an equally distributed palette of 10 colors.
palette = generate_colors(base_color="#db45f9", n=10)
print(palette)
# Example output: ['#db45f9', '#c4f95d', '#6cf95d', '#5d9ef9', ...]
This function leverages color space conversions (RGB ↔ HLS) to evenly distribute hues, ensuring that the generated colors are well balanced while maintaining the original color's lightness and saturation.