www.pythonware.com

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:

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")
Why this matters for clean scripting: Utilizing names and strings instead of hardcoding raw number sets keeps your code easy to read and manage. It eliminates manual color conversion math from your development pipeline.