Skip to content

Commit 2264418

Browse files
committed
Fix assertion observed when adding new colors to an indexed-color TIFF
When ImagePalette._new_color_index adds a new color to an indexed-color TIFF, an assertion added in f2302ab could be tripped. The call into Image.histogram could result in ImageFile.load being called, which could eventually replace ImagePalette._palette with a bytes object, which did not satisfy the assertion that it be only bytearray.
1 parent ec40c54 commit 2264418

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

Tests/test_tiff_palette.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from __future__ import annotations
2+
3+
import io
4+
5+
from PIL import Image, ImageDraw
6+
7+
8+
def test_tiff_palette() -> None:
9+
image = Image.new("P", (3, 1))
10+
file = io.BytesIO()
11+
image.save(file, "tiff")
12+
13+
image = Image.open(file)
14+
draw = ImageDraw.Draw(image)
15+
COLOR_0 = (1, 2, 3)
16+
COLOR_1 = (127, 128, 129)
17+
COLOR_2 = (252, 253, 254)
18+
draw.point((0, 0), fill=COLOR_0)
19+
draw.point((1, 0), fill=COLOR_1)
20+
draw.point((2, 0), fill=COLOR_2)
21+
22+
converted_data = list(image.convert("RGB").getdata())
23+
assert len(converted_data) == 3
24+
assert converted_data[0] == COLOR_0
25+
assert converted_data[1] == COLOR_1
26+
assert converted_data[2] == COLOR_2

src/PIL/ImagePalette.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def getcolor(
166166
except KeyError as e:
167167
# allocate new color slot
168168
index = self._new_color_index(image, e)
169-
assert isinstance(self._palette, bytearray)
169+
assert isinstance(self._palette, (bytes, bytearray))
170170
self.colors[color] = index
171171
if index * 3 < len(self.palette):
172172
self._palette = (

0 commit comments

Comments
 (0)