From ec198899f694544ff0736c525a7424115dd38db2 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 11 Dec 2021 16:23:37 +1100 Subject: [PATCH] Limit quantized palette to number of colors --- Tests/test_image_quantize.py | 7 +++++++ src/PIL/Image.py | 3 ++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Tests/test_image_quantize.py b/Tests/test_image_quantize.py index bd9db362c6c..0be7feac5ca 100644 --- a/Tests/test_image_quantize.py +++ b/Tests/test_image_quantize.py @@ -77,6 +77,13 @@ def test_quantize_dither_diff(): assert dither.tobytes() != nodither.tobytes() +def test_colors(): + im = hopper() + colors = 2 + converted = im.quantize(colors) + assert len(converted.palette.palette) == colors * len("RGB") + + def test_transparent_colors_equal(): im = Image.new("RGBA", (1, 2), (0, 0, 0, 0)) px = im.load() diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 0fca3fa5cc4..0f3b6fada37 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -1111,7 +1111,8 @@ def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1): from . import ImagePalette mode = im.im.getpalettemode() - im.palette = ImagePalette.ImagePalette(mode, im.im.getpalette(mode, mode)) + palette = im.im.getpalette(mode, mode)[: colors * len(mode)] + im.palette = ImagePalette.ImagePalette(mode, palette) return im