Skip to content

Commit 8f86212

Browse files
chuenchen309clauderadarhere
authored
Fix adding a new color when image palette has missing background or transparency index (#9799)
Signed-off-by: Andrew Chen <48723787+chuenchen309@users.noreply.github.com> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: Andrew Murray <radarhere@users.noreply.github.com>
1 parent be48bcb commit 8f86212

2 files changed

Lines changed: 10 additions & 2 deletions

File tree

Tests/test_imagepalette.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,13 +87,17 @@ def test_getcolor_not_special(index: int, palette: ImagePalette.ImagePalette) ->
8787

8888
# Do not use transparency index as a new color
8989
im.info["transparency"] = index
90-
index1 = palette.getcolor((0, 0, 0), im)
90+
index1 = palette.getcolor((0, 0, 1), im)
9191
assert index1 != index
92+
roundtripped_palette = ImagePalette.ImagePalette(palette=palette.palette)
93+
assert roundtripped_palette.colors[(0, 0, 1)] == index1
9294

9395
# Do not use background index as a new color
9496
im.info["background"] = index1
95-
index2 = palette.getcolor((0, 0, 1), im)
97+
index2 = palette.getcolor((0, 0, 2), im)
9698
assert index2 not in (index, index1)
99+
roundtripped_palette = ImagePalette.ImagePalette(palette=palette.palette)
100+
assert roundtripped_palette.colors[(0, 0, 2)] == index2
97101

98102

99103
def test_file(tmp_path: Path) -> None:

src/PIL/ImagePalette.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,11 @@ def _new_color_index(
125125
image.info.get("background"),
126126
image.info.get("transparency"),
127127
)
128+
assert isinstance(self._palette, bytearray)
128129
while index in special_colors:
130+
# Background or transparency index points past the end of the palette.
131+
# Set it to black, so that the new color can be written afterwards.
132+
self._palette += bytearray(len(self.mode))
129133
index += 1
130134
if index >= 256:
131135
if image:

0 commit comments

Comments
 (0)