Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: keep alpha channel for images with mode P and custom transparency #56

Merged
merged 1 commit into from
Jul 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/pillow_avif/AvifImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
16 changes: 15 additions & 1 deletion tests/test_file_avif.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

import pytest

from PIL import Image
from PIL import Image, ImageDraw
from pillow_avif import AvifImagePlugin

from .helper import (
Expand Down Expand Up @@ -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
Expand Down
Loading