From ad12caecda408aae101a9e59f0efd8b1be4e6744 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 25 Sep 2023 20:28:25 +1000 Subject: [PATCH] Convert RGBA palette to RGBA image when saving WebP --- Tests/test_file_webp.py | 10 ++++++++++ src/PIL/WebPImagePlugin.py | 7 +------ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/Tests/test_file_webp.py b/Tests/test_file_webp.py index 3832441c02d..c8e4e6aece0 100644 --- a/Tests/test_file_webp.py +++ b/Tests/test_file_webp.py @@ -234,3 +234,13 @@ def test_duration(self, tmp_path): with Image.open(out_webp) as reloaded: assert reloaded.info["duration"] == 1000 + + def test_roundtrip_rgba_palette(self, tmp_path): + temp_file = str(tmp_path / "temp.webp") + im = Image.new("RGBA", (1, 1)).convert("P") + assert im.mode == "P" + assert im.palette.mode == "RGBA" + im.save(temp_file) + + with Image.open(temp_file) as im: + assert im.getpixel((0, 0)) == (0, 0, 0, 0) diff --git a/src/PIL/WebPImagePlugin.py b/src/PIL/WebPImagePlugin.py index a6e1a2a00c5..86169b78085 100644 --- a/src/PIL/WebPImagePlugin.py +++ b/src/PIL/WebPImagePlugin.py @@ -332,12 +332,7 @@ def _save(im, fp, filename): exact = 1 if im.encoderinfo.get("exact") else 0 if im.mode not in _VALID_WEBP_LEGACY_MODES: - alpha = ( - "A" in im.mode - or "a" in im.mode - or (im.mode == "P" and "transparency" in im.info) - ) - im = im.convert("RGBA" if alpha else "RGB") + im = im.convert("RGBA" if im.has_transparency_data() else "RGB") data = _webp.WebPEncode( im.tobytes(),