Skip to content

Commit 191dc55

Browse files
committed
Simplified code
1 parent 3f9d6f1 commit 191dc55

2 files changed

Lines changed: 15 additions & 23 deletions

File tree

Tests/test_imagecolor.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -200,13 +200,11 @@ def test_color_hsv() -> None:
200200

201201

202202
@pytest.mark.parametrize("mode, premultiplied_mode", (("LA", "La"), ("RGBA", "RGBa")))
203-
@pytest.mark.parametrize("color", ("red", "#ff000080"))
204-
def test_color_premultiplied(mode: str, premultiplied_mode: str, color: str) -> None:
205-
# The premultiplied modes are spelled with a lowercase "a", so an
206-
# uppercase-only check drops their alpha. Compare against convert().
207-
expected = (
208-
Image.new(mode, (1, 1), color).convert(premultiplied_mode).getpixel((0, 0))
209-
)
203+
@pytest.mark.parametrize("color", ("#f00", "#ff000080"))
204+
def test_color_premultiplied_alpha(mode: str, premultiplied_mode: str, color: str) -> None:
205+
im = Image.new(mode, (1, 1), color)
206+
im_premultiplied = im.convert(premultiplied_mode)
207+
expected = im_premultiplied.getpixel((0, 0))
210208

211209
assert ImageColor.getcolor(color, premultiplied_mode) == expected
212210

src/PIL/ImageColor.py

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -152,26 +152,20 @@ def getcolor(color: str, mode: str) -> int | tuple[int, ...]:
152152
r, g, b = rgb
153153
h, s, v = rgb_to_hsv(r / 255, g / 255, b / 255)
154154
return int(h * 255), int(s * 255), int(v * 255)
155-
elif Image.getmodebase(mode) == "L":
155+
if Image.getmodebase(mode) == "L":
156156
r, g, b = rgb
157157
# ITU-R Recommendation 601-2 for nonlinear RGB
158158
# scaled to 24 bits to match the convert's implementation.
159159
graylevel = (r * 19595 + g * 38470 + b * 7471 + 0x8000) >> 16
160-
if mode[-1] == "A":
161-
return graylevel, alpha
162-
if mode[-1] == "a":
163-
return _premultiply(graylevel, alpha), alpha
164-
return graylevel
165-
elif mode[-1] == "A":
166-
return rgb + (alpha,)
167-
elif mode[-1] == "a":
168-
return tuple(_premultiply(band, alpha) for band in rgb) + (alpha,)
169-
return rgb
170-
171-
172-
def _premultiply(band: int, alpha: int) -> int:
173-
# Rounded, to match convert()'s premultiplication.
174-
return (band * alpha + 127) // 255
160+
value = (graylevel,)
161+
else:
162+
value = rgb
163+
if mode[-1] == "a":
164+
# Rounded, to match convert()'s premultiplication.
165+
value = tuple((band * alpha + 127) // 255 for band in value)
166+
if mode[-1] in ("A", "a"):
167+
return value + (alpha,)
168+
return value[0] if len(value) == 1 else value
175169

176170

177171
colormap: dict[str, str | tuple[int, int, int]] = {

0 commit comments

Comments
 (0)