Skip to content

Commit

Permalink
Merge pull request #6654 from jsbueno/fix6652/imagepalette_rgba_color
Browse files Browse the repository at this point in the history
Raise an error when allocating translucent color to RGB palette
  • Loading branch information
radarhere committed Oct 10, 2022
2 parents 91e820f + 9133f35 commit 10edb29
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
7 changes: 4 additions & 3 deletions Tests/test_image_access.py
Expand Up @@ -345,13 +345,14 @@ def test_reference_counting(self):

@pytest.mark.parametrize("mode", ("P", "PA"))
def test_p_putpixel_rgb_rgba(self, mode):
for color in [(255, 0, 0), (255, 0, 0, 127)]:
for color in ((255, 0, 0), (255, 0, 0, 127 if mode == "PA" else 255)):
im = Image.new(mode, (1, 1))
access = PyAccess.new(im, False)
access.putpixel((0, 0), color)

alpha = color[3] if len(color) == 4 and mode == "PA" else 255
assert im.convert("RGBA").getpixel((0, 0)) == (255, 0, 0, alpha)
if len(color) == 3:
color += (255,)
assert im.convert("RGBA").getpixel((0, 0)) == color


class TestImagePutPixelError(AccessTest):
Expand Down
10 changes: 10 additions & 0 deletions Tests/test_imagepalette.py
Expand Up @@ -50,6 +50,16 @@ def test_getcolor():
palette.getcolor("unknown")


def test_getcolor_rgba_color_rgb_palette():
palette = ImagePalette.ImagePalette("RGB")

# Opaque RGBA colors are converted
assert palette.getcolor((0, 0, 0, 255)) == palette.getcolor((0, 0, 0))

with pytest.raises(ValueError):
palette.getcolor((0, 0, 0, 128))


@pytest.mark.parametrize(
"index, palette",
[
Expand Down
6 changes: 5 additions & 1 deletion src/PIL/ImagePalette.py
Expand Up @@ -115,7 +115,11 @@ def getcolor(self, color, image=None):
raise ValueError("palette contains raw palette data")
if isinstance(color, tuple):
if self.mode == "RGB":
if len(color) == 4 and color[3] == 255:
if len(color) == 4:
if color[3] != 255:
raise ValueError(
"cannot add non-opaque RGBA color to RGB palette"
)
color = color[:3]
elif self.mode == "RGBA":
if len(color) == 3:
Expand Down

0 comments on commit 10edb29

Please sign in to comment.