From fb3a89c03e57e0d4ced236f799b0e2ce08f4a82a Mon Sep 17 00:00:00 2001 From: Frankie Dintino Date: Sun, 7 Jul 2024 16:36:53 -0400 Subject: [PATCH] fix: keep alpha channel for images with mode P and custom transparency (#56) fixes #48 --- src/pillow_avif/AvifImagePlugin.py | 4 ++++ tests/test_file_avif.py | 16 +++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/pillow_avif/AvifImagePlugin.py b/src/pillow_avif/AvifImagePlugin.py index e888b71..7dcb064 100644 --- a/src/pillow_avif/AvifImagePlugin.py +++ b/src/pillow_avif/AvifImagePlugin.py @@ -233,6 +233,10 @@ def _save(im, fp, filename, save_all=False): "A" in ims.mode or "a" in ims.mode or (ims.mode == "P" and "A" in ims.im.getpalettemode()) + or ( + ims.mode == "P" + and ims.info.get("transparency", None) is not None + ) ) rawmode = "RGBA" if alpha else "RGB" frame = ims.convert(rawmode) diff --git a/tests/test_file_avif.py b/tests/test_file_avif.py index 8c0096e..771b08a 100644 --- a/tests/test_file_avif.py +++ b/tests/test_file_avif.py @@ -11,7 +11,7 @@ import pytest -from PIL import Image +from PIL import Image, ImageDraw from pillow_avif import AvifImagePlugin from .helper import ( @@ -565,6 +565,20 @@ def test_decoder_upsampling_invalid(self): finally: AvifImagePlugin.CHROMA_UPSAMPLING = "auto" + def test_p_mode_transparency(self): + im = Image.new("P", size=(64, 64)) + draw = ImageDraw.Draw(im) + draw.rectangle(xy=[(0, 0), (32, 32)], fill=255) + draw.rectangle(xy=[(32, 32), (64, 64)], fill=255) + + buf_png = BytesIO() + im.save(buf_png, format="PNG", transparency=0) + im_png = Image.open(buf_png) + buf_out = BytesIO() + im_png.save(buf_out, format="AVIF", quality=100) + + assert_image_similar(im_png.convert("RGBA"), Image.open(buf_out), 1) + class TestAvifAnimation: @contextmanager