The ImageColor Module
When working with digital images in Python using the Python Imaging Library (PIL) or Pillow, one of the most common tasks is specifying colors. Whether you are generating a fresh background canvas or drawing borders on an image template, your program needs to understand color data formatting.
The ImageColor module contains conversion tables and helpful parsing formulas that read CSS3-style color strings and change them into clean math-friendly RGB tuples. This module runs silently in the background whenever you pass color arguments to functions like Image.new() or tools inside the ImageDraw framework.
Supported Color Formats
You don't have to guess or manually calculate hard numbers for colors. The ImageColor module recognizes several simple string types that you likely already know from basic HTML and CSS classes:
- Hexadecimal Codes: Standard web strings written as
"#rgb"or"#rrggbb". For example,"#ff0000"outputs pure red, while"#0000ff"gives pure blue. - RGB Functions: Written exactly like CSS rules:
"rgb(red, green, blue)"using numbers from 0 to 255. You can also use percentages if you prefer, like"rgb(100%, 0%, 0%)". - HSL Color Functions: Given as
"hsl(hue, saturation%, lightness%)". Hue is measured as a circle angle between 0 and 360 (Red is 0, Green is 120, Blue is 240). Saturation sets color richness, and Lightness goes from pure black to pure white. - Common English Color Names: The module understands roughly 140 classic color strings based on X11 and popular web browsers. These are case-insensitive, so writing
"red","Red", or"RED"gives you the exact same output value.
Module Functions
getrgb
ImageColor.getrgb(color) -> (red, green, blue)
This function processes a color string argument and translates it into a standard 3-number Python tuple. If the string format does not match any valid patterns, the code stops and triggers a ValueError exception.
getcolor
ImageColor.getcolor(color, mode) -> (red, green, blue) or integer
This function operates similarly to getrgb, but includes a mode property check. If your image configuration uses a grayscale layout (like "L" or "1"), the color value is automatically condensed into a single gray pixel integer instead of an explicit RGB channel block.
Simple Code Example
Here is how you can use the module within a direct script to build a custom color-blocked background element:
from PIL import Image, ImageColor
# Convert a web-style color string to an RGB tuple
sky_blue_rgb = ImageColor.getrgb("skyblue")
print(sky_blue_rgb) # Outputs: (135, 206, 235)
# Build a clean blank canvas using a CSS3 hex string
new_canvas = Image.new("RGB", (400, 300), "#4b0082")
new_canvas.save("indigo_box.png")