Skip to content

Commit

Permalink
fix: keep alpha channel for images with mode P and custom transparency (
Browse files Browse the repository at this point in the history
#56)

fixes #48
  • Loading branch information
fdintino authored Jul 7, 2024
1 parent b9e95bb commit fb3a89c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
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

0 comments on commit fb3a89c

Please sign in to comment.