Python Imaging Library (Fork) providing comprehensive image processing capabilities for reading, writing, and manipulating images across dozens of formats.
—
Comprehensive color conversion and name resolution utilities for handling CSS-style color strings, named colors, and conversion between different color formats and image modes.
Convert color strings in various formats to RGB/RGBA tuples.
def getrgb(color: str) -> tuple[int, int, int] | tuple[int, int, int, int]:
"""
Convert a color string to an RGB or RGBA tuple.
Parameters:
- color (str): Color string in various formats:
- Named colors: "red", "blue", "lightblue", etc.
- Hex: "#RGB", "#RGBA", "#RRGGBB", "#RRGGBBAA"
- CSS RGB: "rgb(255, 0, 0)", "rgb(100%, 0%, 0%)"
- CSS RGBA: "rgba(255, 0, 0, 255)"
- CSS HSL: "hsl(120, 100%, 50%)"
- CSS HSV/HSB: "hsv(120, 100%, 100%)"
Returns:
tuple: RGB tuple (r, g, b) or RGBA tuple (r, g, b, a)
Raises:
ValueError: If the color string cannot be parsed
"""Convert color strings to values appropriate for specific image modes.
def getcolor(color: str, mode: str) -> int | tuple[int, ...]:
"""
Convert a color string to a value suitable for the given image mode.
Parameters:
- color (str): Color string (same formats as getrgb)
- mode (str): Target image mode ("RGB", "RGBA", "L", "LA", "HSV", etc.)
Returns:
int | tuple: Color value appropriate for the mode:
- "L": grayscale integer
- "LA": (grayscale, alpha) tuple
- "RGB": (red, green, blue) tuple
- "RGBA": (red, green, blue, alpha) tuple
- "HSV": (hue, saturation, value) tuple
- Other modes: converted appropriately
Raises:
ValueError: If the color string cannot be parsed
"""The module includes a comprehensive colormap with 140+ named colors from the CSS4 specification, including:
from PIL import ImageColor
# Parse different color formats
rgb = ImageColor.getrgb("red") # (255, 0, 0)
rgb = ImageColor.getrgb("#ff0000") # (255, 0, 0)
rgb = ImageColor.getrgb("#f00") # (255, 0, 0)
rgba = ImageColor.getrgb("#ff000080") # (255, 0, 0, 128)
rgb = ImageColor.getrgb("rgb(255, 0, 0)") # (255, 0, 0)
rgb = ImageColor.getrgb("rgb(100%, 0%, 0%)") # (255, 0, 0)
rgba = ImageColor.getrgb("rgba(255, 0, 0, 128)") # (255, 0, 0, 128)
rgb = ImageColor.getrgb("hsl(0, 100%, 50%)") # (255, 0, 0)
rgb = ImageColor.getrgb("hsv(0, 100%, 100%)") # (255, 0, 0)
# Convert for specific modes
gray = ImageColor.getcolor("red", "L") # 76 (grayscale)
gray_alpha = ImageColor.getcolor("red", "LA") # (76, 255)
rgb = ImageColor.getcolor("red", "RGB") # (255, 0, 0)
rgba = ImageColor.getcolor("red", "RGBA") # (255, 0, 0, 255)
hsv = ImageColor.getcolor("red", "HSV") # (0, 255, 255)
# Use with image creation
from PIL import Image
img = Image.new("RGB", (100, 100), ImageColor.getcolor("lightblue", "RGB"))Install with Tessl CLI
npx tessl i tessl/pypi-pillow