diff --git a/Tests/test_imagepalette.py b/Tests/test_imagepalette.py index 475d249ed..0583154f7 100644 --- a/Tests/test_imagepalette.py +++ b/Tests/test_imagepalette.py @@ -50,6 +50,15 @@ def test_getcolor(): palette.getcolor("unknown") +def test_getcolor_raises_on_incompatible_color(): + palette = ImagePalette.ImagePalette(mode="RGB") + # Opaque RGBA colors should work + palette.getcolor((0, 0, 0, 255)) + assert palette.getcolor((0, 0, 0)) == palette.getcolor((0, 0, 0, 255)) + with pytest.raises(ValueError): + palette.getcolor((0, 0, 0, 128)) + + @pytest.mark.parametrize( "index, palette", [ diff --git a/src/PIL/ImagePalette.py b/src/PIL/ImagePalette.py index b73b2cd9d..e407bbcd1 100644 --- a/src/PIL/ImagePalette.py +++ b/src/PIL/ImagePalette.py @@ -114,9 +114,13 @@ class ImagePalette: if self.rawmode: raise ValueError("palette contains raw palette data") if isinstance(color, tuple): - if self.mode == "RGB": - if len(color) == 4 and color[3] == 255: + if self.mode == "RGB" and len(color) == 4: + if color[3] == 255: color = color[:3] + else: + raise ValueError( + "RGB ImagePalette can't handle non-opaque RGBA colors" + ) elif self.mode == "RGBA": if len(color) == 3: color += (255,)