From 59b08e4a8a09f91b735ef7f5f65a29a659bbde95 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 30 Nov 2021 20:21:54 +1100 Subject: [PATCH] When saving RGBA, make use of first transparent palette entry --- Tests/test_file_gif.py | 10 ++++++++++ src/PIL/GifImagePlugin.py | 8 +++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py index fae7e912c8c..27c5e1f5631 100644 --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -927,3 +927,13 @@ def test_missing_background(): with Image.open("Tests/images/missing_background.gif") as im: im.seek(1) assert_image_equal_tofile(im, "Tests/images/missing_background_first_frame.gif") + + +def test_saving_rgba(tmp_path): + out = str(tmp_path / "temp.gif") + with Image.open("Tests/images/transparent.png") as im: + im.save(out) + + with Image.open(out) as reloaded: + reloaded_rgba = reloaded.convert("RGBA") + assert reloaded_rgba.load()[0, 0][3] == 0 diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py index 5b466884470..18c493797f4 100644 --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -370,7 +370,13 @@ def _normalize_mode(im, initial_call=False): palette_size = 256 if im.palette: palette_size = len(im.palette.getdata()[1]) // 3 - return im.convert("P", palette=Image.ADAPTIVE, colors=palette_size) + im = im.convert("P", palette=Image.ADAPTIVE, colors=palette_size) + if im.palette.mode == "RGBA": + for rgba in im.palette.colors.keys(): + if rgba[3] == 0: + im.info["transparency"] = im.palette.colors[rgba] + break + return im else: return im.convert("P") return im.convert("L")