Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Image.save(append_images) cropping using bg color instead of alpha #7207

@viotalJiplk

Description

@viotalJiplk

What did you do?

I used Image.save(append_images=[]) to generate gif but it cropped part of the image (got boundary box of the image wrong). It throws away alpha when preparing to add image and then it relies only on bg color, which does not work when the image has the same color as background.

What are your OS, Python and Pillow versions?

  • OS: Linux (Debian GNU/Linux 12 (bookworm) x86_64)
  • Python: 3.11.2
  • Pillow: 9.5.0

code:

from PIL import Image, ImageDraw

with Image.open('testin3.png') as avatar:
    frames = []
    deformWidth = [-1, -2]
    deformHeight = [4, 3]
    width, height = 80, 80
    x, y = 112, 122

    for i in range(2):
        frame = Image.new("RGBA", (x, y), (0, 0, 0, 0))
        width = width - deformWidth[i]
        height = height - deformHeight[i]
        avatar = avatar.resize((width, height))
        avatar = avatar.convert("P", palette=Image.ADAPTIVE, colors=200).convert("RGBA")

        frame.paste(avatar, (x - width, y - height), avatar)
        frames.append(frame)

    frames[0].save(
        "testout.gif",
        save_all=True,
        append_images=frames[1:],
        duration=400,
        loop=0,
        transparency=0,
        disposal=2,
        optimize=False
    )

testin3.png: testin3

testout.gif: testout

It could be solved by this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions