Skip to content

Update transparency when quantizing - #10720

Open
mh-masum6875 wants to merge 2 commits into
python-pillow:mainfrom
mh-masum6875:fix/quantize-transparency
Open

mh-masum6875 wants to merge 2 commits into
python-pillow:mainfrom
mh-masum6875:fix/quantize-transparency

Conversation

@mh-masum6875

Copy link
Copy Markdown

Changes proposed in this pull request:

  • quantize() copies info["transparency"] to the new P image unchanged. For an RGB image that's an RGB tuple, so the result can't be converted to RGBA or saved as GIF. For L and P images, it's an index into the old values, so the wrong palette entry is transparent, or none at all.
  • After quantizing, I look for the transparent color in the new palette and use its index. If the color isn't in the palette, the transparency is removed.
  • quantize(palette=...) on an L image is unchanged, as the pixel values are kept as the palette indexes there.
from PIL import Image

im = Image.new("RGB", (2, 1))
im.putpixel((0, 0), (255, 0, 0))
im.info["transparency"] = (255, 0, 0)  # as read from an RGB PNG with tRNS

converted = im.quantize()
print(converted.info)  # {'transparency': (255, 0, 0)}
converted.convert("RGBA")
# ValueError: Transparency for P mode should be bytes or int

I only ran this against the 13.0.0 wheel with the change applied on top, as I don't have a C toolchain set up here.

@suirindo

suirindo commented Dec 3, 2026

Copy link
Copy Markdown

Could we cover palette images with a byte-valued alpha table before dropping it here? On Pillow 13.0.0, a 3-pixel P image with a white/gray/black palette, indices (0, 1, 2) and transparency=bytes([0, 128, 255]) retains those indices and per-pixel alpha after quantize(colors=3). Applying the pinned _quantize_transparency() from 4e127ec at the same boundary changes the RGBA alpha to (255, 255, 255), even though the indices did not move. A regression test comparing RGBA alpha would cover this case. AI-assisted review; installed Pillow wheel plus the pinned helper, not a full PR build.

@mh-masum6875

Copy link
Copy Markdown
Author

Good catch, thanks. I reproduced it, your example lost its alpha with my change.

Leaving the bytes as they were doesn't work in general though, the palette order usually moves and the old table then points at the wrong colors. I pushed a commit that carries each color's alpha over to its new position, plus tests for your case and one where the order changes.

One limit: if quantizing merges colors, those come out opaque.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants