Python Pillow - Colors on an Image



The ImageColor module contains colors in different format arranged in tables and it also contains converters from CSS3-style color specifiers to RGB tuples.

Color Names

The ImageColor module supports the following strings formats −

  • Hexadecimal color specifiers, given as #rgb or #rrggbb. For example, #00ff00 represents pure green.

  • #00ff00 hex color, red value is 0 (0% red), green value is 255(100% green) and the blue value of its RGB is 0 (0% blue).

  • Cylindrical – coordinate representations (also referred to as HSL) of color #00ff00 hue: 0.33, saturation: 1.00 and also the lightness value of 00ff00 is 0.50.

  • The Image Color module provides around 140 standard color names, based on the color’s supported by the X Window system and most web browsers. Color names are case insensitive.

ImageColor.getrgb() Method

Convert a color string to an RGB tuple. If the string cannot be parsed, a ValueError exception is raised by this function.

Syntax

PIL.ImageColor.getrgb(color)

Where,

  • Arguments: color – A color string

  • Return Value: (red, green, blue[, alpha])

Example 1

from PIL import ImageColor

# using getrgb
img = ImageColor.getrgb("blue")
print(img)

img1 = ImageColor.getrgb("purple")
print(img1)

Output

(0, 0, 255)
(128, 0, 128)

Example 2

#Import required image modules
from PIL import Image,ImageColor

# Create new image & get color RGB tuple.
img = Image.new("RGB", (256, 256), ImageColor.getrgb("#add8e6"))

#Show image
img.show()

Output

ImageColor getrgb

ImageColor. getcolor() Method

This method is same as getrgb(), however, converts the RGB value to a greyscale value, if the mode isn’t The graphics commands support shape drawing and text annotation color or a palette image. If the string cannot be parsed, this function raises a ValueError exception.

Syntax

PIL.ImageColor.getcolor(color, mode)

Where,

  • Arguments - A color string

  • Return Value - (graylevel[, alpha]) or (red, green, blue[, alpha])

Example

#Import required image modules
from PIL import Image,ImageColor

# using getrgb

img = ImageColor.getrgb("skyblue")
print(img)

img1 = ImageColor.getrgb("purple")
print(img1)

Output

(135, 206, 235)
(128, 0, 128)
Advertisements