From 456aab18ff4745c3cf645a3bc5663ffba39aabec Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 5 Dec 2021 14:06:44 +1100 Subject: [PATCH] Fixed palette index for zeroed color after FASTOCTREE quantize --- Tests/test_image_quantize.py | 25 +++++++++++++++++++++++++ src/PIL/Image.py | 7 +++++++ 2 files changed, 32 insertions(+) diff --git a/Tests/test_image_quantize.py b/Tests/test_image_quantize.py index bd9db362c6c..ccb4095dcef 100644 --- a/Tests/test_image_quantize.py +++ b/Tests/test_image_quantize.py @@ -85,3 +85,28 @@ def test_transparent_colors_equal(): converted = im.quantize() converted_px = converted.load() assert converted_px[0, 0] == converted_px[0, 1] + + +@pytest.mark.parametrize( + "method, color", + ( + (Image.MEDIANCUT, (0, 0, 0)), + (Image.MAXCOVERAGE, (0, 0, 0)), + (Image.FASTOCTREE, (0, 0, 0)), + (Image.LIBIMAGEQUANT, (0, 0, 0)), + (Image.FASTOCTREE, (0, 0, 0, 0)), + (Image.LIBIMAGEQUANT, (0, 0, 0, 0)), + ), +) +def test_palette(method, color): + im = Image.new("RGBA" if len(color) == 4 else "RGB", (1, 1), color) + + try: + converted = im.quantize(method=method) + except ValueError as ex: # pragma: no cover + if "dependency" in str(ex).lower(): + pytest.skip("libimagequant support not available") + else: + raise + converted_px = converted.load() + assert converted_px[0, 0] == converted.palette.colors[color] diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 0fca3fa5cc4..5a1e5649fbf 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -1112,6 +1112,13 @@ def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1): mode = im.im.getpalettemode() im.palette = ImagePalette.ImagePalette(mode, im.im.getpalette(mode, mode)) + if method == FASTOCTREE: + mode_len = len(mode) + color = (0,) * mode_len + if color in im.palette.colors and im.palette.palette.endswith( + b"\x00" * mode_len + ): + im.palette.colors[color] = 255 return im