From e7fab6abf44faf3bdf45b99c239bf38569a1ece4 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 29 Aug 2022 23:20:31 +1000 Subject: [PATCH 1/2] Fixed remapping to palette with duplicate entries --- Tests/test_file_gif.py | 13 +++++++++++++ src/PIL/GifImagePlugin.py | 2 ++ 2 files changed, 15 insertions(+) diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py index 68cb8a36e8d..4e967faec91 100644 --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -1087,6 +1087,19 @@ def test_palette_save_P(tmp_path): assert_image_equal(reloaded, im) +def test_palette_save_duplicate_entries(tmp_path): + im = Image.new("P", (1, 2)) + im.putpixel((0, 1), 1) + + im.putpalette((0, 0, 0, 0, 0, 0)) + + out = str(tmp_path / "temp.gif") + im.save(out, palette=[0, 0, 0, 0, 0, 0, 1, 1, 1]) + + with Image.open(out) as reloaded: + assert reloaded.convert("RGB").getpixel((0, 1)) == (0, 0, 0) + + def test_palette_save_all_P(tmp_path): frames = [] colors = ((255, 0, 0), (0, 255, 0)) diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py index 2e11df54c0a..40fbaa9b568 100644 --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -523,6 +523,8 @@ def _normalize_palette(im, palette, info): index = im.palette.colors[source_color] except KeyError: index = None + if index in used_palette_colors: + index = None used_palette_colors.append(index) for i, index in enumerate(used_palette_colors): if index is None: From 841ba4a940b2b09b5c07a43c7a75ce1266d0f2c9 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 30 Aug 2022 08:08:01 +1000 Subject: [PATCH 2/2] Simplified code --- src/PIL/GifImagePlugin.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py index 40fbaa9b568..20435fe313a 100644 --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -519,10 +519,7 @@ def _normalize_palette(im, palette, info): used_palette_colors = [] for i in range(0, len(source_palette), 3): source_color = tuple(source_palette[i : i + 3]) - try: - index = im.palette.colors[source_color] - except KeyError: - index = None + index = im.palette.colors.get(source_color) if index in used_palette_colors: index = None used_palette_colors.append(index)