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

Do not use background or transparency index for new color #5564

Merged
merged 2 commits into from Jun 30, 2021
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
23 changes: 23 additions & 0 deletions Tests/test_imagepalette.py
Expand Up @@ -49,6 +49,29 @@ def test_getcolor():
palette.getcolor("unknown")


@pytest.mark.parametrize(
"index, palette",
[
# Test when the palette is not full
(0, ImagePalette.ImagePalette()),
# Test when the palette is full
(255, ImagePalette.ImagePalette("RGB", list(range(256)) * 3)),
],
)
def test_getcolor_not_special(index, palette):
im = Image.new("P", (1, 1))

# Do not use transparency index as a new color
im.info["transparency"] = index
index1 = palette.getcolor((0, 0, 0), im)
assert index1 != index

# Do not use background index as a new color
im.info["background"] = index1
index2 = palette.getcolor((0, 0, 1), im)
assert index2 not in (index, index1)


def test_file(tmp_path):

palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3)
Expand Down
10 changes: 9 additions & 1 deletion src/PIL/ImagePalette.py
Expand Up @@ -118,11 +118,19 @@ def getcolor(self, color, image=None):
if not isinstance(self.palette, bytearray):
self._palette = bytearray(self.palette)
index = len(self.palette) // 3
special_colors = ()
if image:
special_colors = (
image.info.get("background"),
image.info.get("transparency"),
)
while index in special_colors:
index += 1
if index >= 256:
if image:
# Search for an unused index
for i, count in reversed(list(enumerate(image.histogram()))):
if count == 0:
if count == 0 and i not in special_colors:
index = i
break
if index >= 256:
Expand Down