'How to check via the Wand binding whether a color string is valid in ImageMagick?

In Wand, the Python binding for ImageMagick I can use color names to create a plain image. For example:

img = Image(width=100, height=50, pseudo=f'xc:yellow')

In the example the string yellow has to be an ImageMagick color string. How can I test beforehand via a Wand method whether the color string is indeed recognized by ImageMagick?



Solution 1:[1]

If you instantiate a Color object with your color string, you get an ValueError exception when the string is not valid. For example:

from wand.color import Color

col = Color('graay')

will raise a ValueError with the message "Unrecognized color string "'graay'".

So you can check for this:

try:
    col = Color('graay')
except ValueError as e:
    print("Don't know about this color")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 halloleo