From cb8956fffb1bc0df9c74b2b789c716c64dd065b6 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Thu, 22 Jun 2023 23:27:45 +1000 Subject: [PATCH] Convert to HSV if mode is HSV in getcolor() --- Tests/test_imagecolor.py | 4 ++++ src/PIL/Image.py | 2 +- src/PIL/ImageColor.py | 16 ++++++++++++---- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/Tests/test_imagecolor.py b/Tests/test_imagecolor.py index dcc44e6e3..2fae6151c 100644 --- a/Tests/test_imagecolor.py +++ b/Tests/test_imagecolor.py @@ -193,6 +193,10 @@ def test_rounding_errors(): Image.new("LA", (1, 1), "white") +def test_color_hsv(): + assert (170, 255, 255) == ImageColor.getcolor("hsv(240, 100%, 100%)", "HSV") + + def test_color_too_long(): # Arrange color_too_long = "hsl(" + "1" * 40 + "," + "1" * 40 + "%," + "1" * 40 + "%)" diff --git a/src/PIL/Image.py b/src/PIL/Image.py index a785292f8..7b31178e3 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -2882,7 +2882,7 @@ def new(mode, size, color=0): :param color: What color to use for the image. Default is black. If given, this should be a single integer or floating point value for single-band modes, and a tuple for multi-band modes (one value - per band). When creating RGB images, you can also use color + per band). When creating RGB or HSV images, you can also use color strings as supported by the ImageColor module. If the color is None, the image is not initialised. :returns: An :py:class:`~PIL.Image.Image` object. diff --git a/src/PIL/ImageColor.py b/src/PIL/ImageColor.py index e184ed68d..befc1fd1d 100644 --- a/src/PIL/ImageColor.py +++ b/src/PIL/ImageColor.py @@ -122,9 +122,11 @@ def getrgb(color): def getcolor(color, mode): """ - Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB value to a - greyscale value if ``mode`` is not color or a palette image. If the string - cannot be parsed, this function raises a :py:exc:`ValueError` exception. + Same as :py:func:`~PIL.ImageColor.getrgb` for most modes. However, if + ``mode`` is HSV, converts the RGB value to a HSV value, or if ``mode`` is + not color or a palette image, converts the RGB value to a greyscale value. + If the string cannot be parsed, this function raises a :py:exc:`ValueError` + exception. .. versionadded:: 1.1.4 @@ -137,7 +139,13 @@ def getcolor(color, mode): if len(color) == 4: color, alpha = color[:3], color[3] - if Image.getmodebase(mode) == "L": + if mode == "HSV": + from colorsys import rgb_to_hsv + + r, g, b = color + h, s, v = rgb_to_hsv(r / 255, g / 255, b / 255) + return int(h * 255), int(s * 255), int(v * 255) + elif Image.getmodebase(mode) == "L": r, g, b = color # ITU-R Recommendation 601-2 for nonlinear RGB # scaled to 24 bits to match the convert's implementation.