Merge pull request #7226 from radarhere/getcolor

This commit is contained in:
Hugo van Kemenade 2023-06-30 09:26:51 +03:00 committed by GitHub
commit 9abef1ad0b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 17 additions and 5 deletions

View File

@ -193,6 +193,10 @@ def test_rounding_errors():
Image.new("LA", (1, 1), "white") 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(): def test_color_too_long():
# Arrange # Arrange
color_too_long = "hsl(" + "1" * 40 + "," + "1" * 40 + "%," + "1" * 40 + "%)" color_too_long = "hsl(" + "1" * 40 + "," + "1" * 40 + "%," + "1" * 40 + "%)"

View File

@ -2885,7 +2885,7 @@ def new(mode, size, color=0):
:param color: What color to use for the image. Default is black. :param color: What color to use for the image. Default is black.
If given, this should be a single integer or floating point value 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 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 strings as supported by the ImageColor module. If the color is
None, the image is not initialised. None, the image is not initialised.
:returns: An :py:class:`~PIL.Image.Image` object. :returns: An :py:class:`~PIL.Image.Image` object.

View File

@ -122,9 +122,11 @@ def getrgb(color):
def getcolor(color, mode): def getcolor(color, mode):
""" """
Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB value to a Same as :py:func:`~PIL.ImageColor.getrgb` for most modes. However, if
greyscale value if ``mode`` is not color or a palette image. If the string ``mode`` is HSV, converts the RGB value to a HSV value, or if ``mode`` is
cannot be parsed, this function raises a :py:exc:`ValueError` exception. 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 .. versionadded:: 1.1.4
@ -137,7 +139,13 @@ def getcolor(color, mode):
if len(color) == 4: if len(color) == 4:
color, alpha = color[:3], color[3] 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 r, g, b = color
# ITU-R Recommendation 601-2 for nonlinear RGB # ITU-R Recommendation 601-2 for nonlinear RGB
# scaled to 24 bits to match the convert's implementation. # scaled to 24 bits to match the convert's implementation.