From 22644181bd1dd6f559b174ed56307b83677bc7a5 Mon Sep 17 00:00:00 2001 From: Mark Mentovai Date: Mon, 24 Nov 2025 12:56:09 -0500 Subject: [PATCH] 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 f2302ab716e9e 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. --- Tests/test_tiff_palette.py | 26 ++++++++++++++++++++++++++ src/PIL/ImagePalette.py | 2 +- 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 Tests/test_tiff_palette.py diff --git a/Tests/test_tiff_palette.py b/Tests/test_tiff_palette.py new file mode 100644 index 00000000000..320f73fcd7e --- /dev/null +++ b/Tests/test_tiff_palette.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +import io + +from PIL import Image, ImageDraw + + +def test_tiff_palette() -> None: + image = Image.new("P", (3, 1)) + file = io.BytesIO() + image.save(file, "tiff") + + image = Image.open(file) + draw = ImageDraw.Draw(image) + COLOR_0 = (1, 2, 3) + COLOR_1 = (127, 128, 129) + COLOR_2 = (252, 253, 254) + draw.point((0, 0), fill=COLOR_0) + draw.point((1, 0), fill=COLOR_1) + draw.point((2, 0), fill=COLOR_2) + + converted_data = list(image.convert("RGB").getdata()) + assert len(converted_data) == 3 + assert converted_data[0] == COLOR_0 + assert converted_data[1] == COLOR_1 + assert converted_data[2] == COLOR_2 diff --git a/src/PIL/ImagePalette.py b/src/PIL/ImagePalette.py index 103697117b9..f901088672d 100644 --- a/src/PIL/ImagePalette.py +++ b/src/PIL/ImagePalette.py @@ -166,7 +166,7 @@ def getcolor( except KeyError as e: # allocate new color slot index = self._new_color_index(image, e) - assert isinstance(self._palette, bytearray) + assert isinstance(self._palette, (bytes, bytearray)) self.colors[color] = index if index * 3 < len(self.palette): self._palette = (