Correct allocating new color to RGBA palette (#9313)

This commit is contained in:
Hugo van Kemenade 2025-11-30 21:57:22 +02:00 committed by GitHub
commit 4a733e5092
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 11 additions and 4 deletions

View File

@ -49,6 +49,12 @@ def test_getcolor() -> None:
palette.getcolor("unknown") # type: ignore[arg-type]
def test_getcolor_rgba() -> None:
palette = ImagePalette.ImagePalette("RGBA", (1, 2, 3, 4))
palette.getcolor((5, 6, 7, 8))
assert palette.palette == b"\x01\x02\x03\x04\x05\x06\x07\x08"
def test_getcolor_rgba_color_rgb_palette() -> None:
palette = ImagePalette.ImagePalette("RGB")

View File

@ -118,7 +118,7 @@ class ImagePalette:
) -> int:
if not isinstance(self.palette, bytearray):
self._palette = bytearray(self.palette)
index = len(self.palette) // 3
index = len(self.palette) // len(self.mode)
special_colors: tuple[int | tuple[int, ...] | None, ...] = ()
if image:
special_colors = (
@ -168,11 +168,12 @@ class ImagePalette:
index = self._new_color_index(image, e)
assert isinstance(self._palette, bytearray)
self.colors[color] = index
if index * 3 < len(self.palette):
mode_len = len(self.mode)
if index * mode_len < len(self.palette):
self._palette = (
self._palette[: index * 3]
self._palette[: index * mode_len]
+ bytes(color)
+ self._palette[index * 3 + 3 :]
+ self._palette[index * mode_len + mode_len :]
)
else:
self._palette += bytes(color)