Skip to content

Commit

Permalink
Merge pull request #7226 from radarhere/getcolor
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk committed Jun 30, 2023
2 parents be4bfaa + cb8956f commit 9abef1a
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
4 changes: 4 additions & 0 deletions Tests/test_imagecolor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 + "%)"
Expand Down
2 changes: 1 addition & 1 deletion src/PIL/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -2885,7 +2885,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.
Expand Down
16 changes: 12 additions & 4 deletions src/PIL/ImageColor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down

0 comments on commit 9abef1a

Please sign in to comment.