Python Pillow – Converting Color String to RGB Color Values


Python Pillow – Converting color string to RGB Color values



”;


Converting a color string to RGB color values is the process of taking a textual representation of a color and converting it into the numerical values that represent the color in the Red, Green and Blue (RGB) color model. In the RGB color model colors are specified by three numbers each ranging from 0 to 255 in which,

  • The first number represents the amount of red in the color.

  • The second number represents the amount of green in the color.

  • The third number represents the amount of blue in the color.

For example, the color red is typically represented as (255, 0, 0) in RGB values which means it has maximum red (255) and no green (0) or no blue (0).

Converting color string to RGB Color values

To perform the conversion of color string into RGB values we can use the getrgb() function in the ImageColor module of the Python Pillow library.

Syntax

The below is the syntax and parameters of the ImageColor.getrgb() method −


ImageColor.getrgb(color)

Where,

  • color − This is a string representing the color we want to convert to RGB values. It can be a color name (e.g., “red”, “blue”) or a hexadecimal color code (e.g., “#00FF00”) or other color representations that Pillow supports.

Example

In this example the ImageColor.getrgb() function takes a color string blue as an argument and returns a tuple of RGB values.


from PIL import ImageColor

#Define a color string
color_string = "blue"

#Convert the color string to RGB values
rgb_color = ImageColor.getrgb(color_string)

#Print the RGB values
print("The conversion of the color string",color_string,":",rgb_color)

Output


The conversion of the color string blue: (0, 0, 255)

Example

Here, in this example we are converting the yellow color string into the RGB values. We are passing the color string argument as a hexadecimal value to the ImageColor.getrgb() method.


from PIL import ImageColor

#Define a color string
color_string = "#FFFF00"

#Convert the color string to RGB values
rgb_color = ImageColor.getrgb(color_string)

#Print the RGB values
print("The conversion of the color string",color_string,":",rgb_color)

Output


The conversion of the color string "#FFFF00": (255, 255, 0)

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *