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

Consider palette size when converting and in getpalette() #6060

Merged
merged 2 commits into from
Feb 18, 2022

Conversation

radarhere
Copy link
Member

Resolves #6046

Investigating the issue, I think it can be stated as two problems.

  1. getpalette() returns more entries than set by putpalette().
>>> from PIL import Image
>>> im = Image.new("P", (1, 1))
>>> im.putpalette((255, 0, 0))
>>> im.getpalette()
[255, 0, 0, 1, 1, 1, 2, 2, 2, ...]

This PR solves this by adding a size member to the C ImagingPaletteInstance.
Fixing this removes the need for trimming the palette in Python in im.load().

  1. Because C was not aware that a palette might have anything less than 256 entries, when converting an image to P, it considers all of the palette entries, rather than limiting itself to the palette size.
from PIL import Image
p = Image.new("P", (1, 1))
p.putpalette((255, 0, 0, 0, 0, 255))  # red and blue
im = Image.open("Tests/images/hopper.png")
im.quantize(palette=p).convert("RGB").save("out.png")
Before After
before after

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Extra output from getpalette() and getcolors() in quantized image
2 participants