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

Ignore non-opaque WebP background when saving as GIF #6792

Merged
merged 1 commit into from Dec 21, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 11 additions & 2 deletions Tests/test_file_gif.py
Expand Up @@ -859,14 +859,23 @@ def test_background(tmp_path):
im.info["background"] = 1
im.save(out)
with Image.open(out) as reread:

assert reread.info["background"] == im.info["background"]


def test_webp_background(tmp_path):
out = str(tmp_path / "temp.gif")

# Test opaque WebP background
if features.check("webp") and features.check("webp_anim"):
with Image.open("Tests/images/hopper.webp") as im:
assert isinstance(im.info["background"], tuple)
assert im.info["background"] == (255, 255, 255, 255)
im.save(out)

# Test non-opaque WebP background
im = Image.new("L", (100, 100), "#000")
im.info["background"] = (0, 0, 0, 0)
im.save(out)


def test_comment(tmp_path):
with Image.open(TEST_GIF) as im:
Expand Down
15 changes: 9 additions & 6 deletions src/PIL/GifImagePlugin.py
Expand Up @@ -886,20 +886,23 @@ def _get_palette_bytes(im):
def _get_background(im, info_background):
background = 0
if info_background:
background = info_background
if isinstance(background, tuple):
if isinstance(info_background, tuple):
# WebPImagePlugin stores an RGBA value in info["background"]
# So it must be converted to the same format as GifImagePlugin's
# info["background"] - a global color table index
try:
background = im.palette.getcolor(background, im)
background = im.palette.getcolor(info_background, im)
except ValueError as e:
if str(e) == "cannot allocate more than 256 colors":
if str(e) not in (
# If all 256 colors are in use,
# then there is no need for the background color
return 0
else:
"cannot allocate more than 256 colors",
# Ignore non-opaque WebP background
"cannot add non-opaque RGBA color to RGB palette",
):
raise
else:
background = info_background
return background


Expand Down