From 1e475ef312dd39c723f8a216fcc93354d349c280 Mon Sep 17 00:00:00 2001 From: nietras <10798831+nietras@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:38:20 +0100 Subject: [PATCH 1/2] Speed up BMP grayscale palette detection Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- Tests/test_file_bmp.py | 103 +++++++++++++++++++++++++++++++++++ docs/releasenotes/13.1.0.rst | 6 ++ src/PIL/BmpImagePlugin.py | 20 ++----- src/PIL/_imaging.pyi | 1 + src/_imaging.c | 44 +++++++++++++++ 5 files changed, 160 insertions(+), 14 deletions(-) diff --git a/Tests/test_file_bmp.py b/Tests/test_file_bmp.py index 7df0c3b610d..d0505c74af5 100644 --- a/Tests/test_file_bmp.py +++ b/Tests/test_file_bmp.py @@ -39,6 +39,109 @@ def test_invalid_file() -> None: BmpImagePlugin.BmpImageFile(fp) +def encode_palette_bmp( + header_size: int, + colors: int, + palette: bytes | bytearray, + pixels: bytes = b"\x00\x01\x7f\xff", +) -> io.BytesIO: + if header_size == 12: + header = o32(12) + o16(4) + o16(1) + o16(1) + o16(8) + else: + header = ( + o32(40) + + o32(4) + + o32(1) + + o16(1) + + o16(8) + + o32(0) + + o32(len(pixels)) + + o32(0) * 2 + + o32(colors) + + o32(0) + ) + offset = 14 + len(header) + len(palette) + return io.BytesIO( + b"BM" + + o32(offset + len(pixels)) + + o32(0) + + o32(offset) + + header + + palette + + pixels + ) + + +@pytest.mark.parametrize("header_size", (12, 40)) +@pytest.mark.parametrize("channel", (0, 1, 2)) +@pytest.mark.parametrize("entry", (None, 0, 1, 127, 255)) +def test_grayscale_palette_detection( + header_size: int, channel: int, entry: int | None +) -> None: + padding = 3 if header_size == 12 else 4 + palette = bytearray() + for value in range(256): + palette.extend(bytes((value, value, value))) + if padding == 4: + palette.append(127) + if entry is not None: + palette[entry * padding + channel] ^= 1 + + with Image.open(encode_palette_bmp(header_size, 256, palette)) as im: + if entry is None: + assert im.mode == "L" + assert im.tobytes() == b"\x00\x01\x7f\xff" + else: + assert im.mode == "P" + expected = bytearray() + for index in (0, 1, 127, 255): + expected.extend(palette[index * padding : index * padding + 3][::-1]) + assert im.convert("RGB").tobytes() == expected + + +@pytest.mark.parametrize("colors", (1, 2, 3, 16, 255, 257, 512)) +def test_grayscale_palette_sizes(colors: int) -> None: + values = (0, 255) if colors == 2 else range(colors) + palette = b"".join(bytes((value & 255,)) * 3 + b"\x7f" for value in values) + with Image.open(encode_palette_bmp(40, colors, palette, b"\x00" * 4)) as im: + assert im.mode == ("1" if colors <= 2 else "L") + assert im.tobytes() == (b"\x00" if colors <= 2 else b"\x00" * 4) + + +def test_two_color_nonidentity_palette() -> None: + palette = b"\x00\x00\x00\x7f\x01\x01\x01\x7f" + with Image.open(encode_palette_bmp(40, 2, palette)) as im: + assert im.mode == "P" + assert im.getpalette() == [0, 0, 0, 1, 1, 1] + + +@pytest.mark.parametrize("padding", (3, 4)) +@pytest.mark.parametrize("colors", (1, 2, 3, 16, 256, 257)) +def test_grayscale_palette_truncation(colors: int, padding: int) -> None: + values = (0, 255) if colors == 2 else range(colors) + palette = b"".join( + bytes((value & 255,)) * 3 + (b"\x7f" if padding == 4 else b"") + for value in values + ) + assert Image.core.is_grayscale_palette(palette, colors, padding) + required = (colors - 1) * padding + 3 + assert Image.core.is_grayscale_palette(palette[:required], colors, padding) + assert not Image.core.is_grayscale_palette(palette[: required - 1], colors, padding) + assert not Image.core.is_grayscale_palette(b"", colors, padding) + + +@pytest.mark.parametrize("colors", (0, -1, 65537)) +def test_grayscale_palette_invalid_size(colors: int) -> None: + with pytest.raises(ValueError, match="palette size"): + Image.core.is_grayscale_palette(b"", colors, 4) + + +@pytest.mark.parametrize("padding", (0, -1, 1, 2, 5)) +def test_grayscale_palette_invalid_padding(padding: int) -> None: + with pytest.raises(ValueError, match="3 or 4 bytes"): + Image.core.is_grayscale_palette(b"", 256, padding) + + def test_fallback_if_mmap_errors() -> None: # This image has been truncated, # so that the buffer is not large enough when using mmap diff --git a/docs/releasenotes/13.1.0.rst b/docs/releasenotes/13.1.0.rst index 22759b2fc72..01a6f99c496 100644 --- a/docs/releasenotes/13.1.0.rst +++ b/docs/releasenotes/13.1.0.rst @@ -67,6 +67,12 @@ Two new image processing operations are available in ImageOps. Other changes ============= +BMP grayscale palette detection +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Grayscale BMP palettes are now checked in native code without temporary allocations, +reducing the overhead of opening small images. + Rounding crop coordinates ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/PIL/BmpImagePlugin.py b/src/PIL/BmpImagePlugin.py index 6de6676a38c..520c3c757f1 100644 --- a/src/PIL/BmpImagePlugin.py +++ b/src/PIL/BmpImagePlugin.py @@ -265,29 +265,21 @@ def _bitmap(self, header: int = 0, offset: int = 0) -> None: # --------------- Once the header is processed, process the palette/LUT if self.mode == "P": # Paletted for 1, 4 and 8 bit images + colors = file_info["colors"] # ---------------------------------------------------- 1-bit images - if not (0 < file_info["colors"] <= 65536): - msg = f"Unsupported BMP Palette size ({file_info['colors']})" + if not (0 < colors <= 65536): + msg = f"Unsupported BMP Palette size ({colors})" raise OSError(msg) else: padding = file_info["palette_padding"] - palette = read(padding * file_info["colors"]) - grayscale = True - indices = ( - (0, 255) - if file_info["colors"] == 2 - else list(range(file_info["colors"])) - ) + palette = read(padding * colors) # ----------------- Check if grayscale and ignore palette if so - for ind, val in enumerate(indices): - rgb = palette[ind * padding : ind * padding + 3] - if rgb != o8(val) * 3: - grayscale = False + grayscale = Image.core.is_grayscale_palette(palette, colors, padding) # ------- If all colors are gray, white or black, ditch palette if grayscale: - self._mode = "1" if file_info["colors"] <= 2 else "L" + self._mode = "1" if colors <= 2 else "L" raw_mode = self.mode else: self._mode = "P" diff --git a/src/PIL/_imaging.pyi b/src/PIL/_imaging.pyi index 8cb6e93e7da..1d7c44b3e42 100644 --- a/src/PIL/_imaging.pyi +++ b/src/PIL/_imaging.pyi @@ -42,6 +42,7 @@ class _Path: def __getattr__(self, name: str) -> Any: ... def font(image: ImagingCore, glyphdata: bytes) -> ImagingFont: ... +def is_grayscale_palette(palette: bytes, colors: int, padding: int, /) -> bool: ... def outline() -> _Outline: ... def path( data: int | _Path | Buffer | Sequence[float] | Sequence[list[float]], diff --git a/src/_imaging.c b/src/_imaging.c index f6a29515269..c83b37fdbc5 100644 --- a/src/_imaging.c +++ b/src/_imaging.c @@ -4258,6 +4258,49 @@ _effect_spread(ImagingObject *self, PyObject *args) { /* UTILITIES */ /* -------------------------------------------------------------------- */ +static PyObject * +_is_grayscale_palette(PyObject *self, PyObject *const *args, Py_ssize_t nargs) { + Py_ssize_t colors, padding, i; + const UINT8 *palette; + + if (nargs != 3) { + PyErr_SetString(PyExc_TypeError, "is_grayscale_palette requires 3 arguments"); + return NULL; + } + if (!PyBytes_Check(args[0])) { + PyErr_SetString(PyExc_TypeError, "palette must be bytes"); + return NULL; + } + colors = PyLong_AsSsize_t(args[1]); + if (colors == -1 && PyErr_Occurred()) { + return NULL; + } + padding = PyLong_AsSsize_t(args[2]); + if (padding == -1 && PyErr_Occurred()) { + return NULL; + } + if (colors < 1 || colors > 65536) { + PyErr_SetString(PyExc_ValueError, "palette size must be between 1 and 65536"); + return NULL; + } + if (padding != 3 && padding != 4) { + PyErr_SetString(PyExc_ValueError, "palette entries must contain 3 or 4 bytes"); + return NULL; + } + if (PyBytes_GET_SIZE(args[0]) < (colors - 1) * padding + 3) { + Py_RETURN_FALSE; + } + palette = (const UINT8 *)PyBytes_AS_STRING(args[0]); + for (i = 0; i < colors; i++, palette += padding) { + UINT8 expected = colors == 2 && i == 1 ? 255 : (UINT8)i; + if (palette[0] != expected || palette[1] != expected || + palette[2] != expected) { + Py_RETURN_FALSE; + } + } + Py_RETURN_TRUE; +} + static PyObject * _getcodecstatus(PyObject *self, PyObject *args) { int status; @@ -5087,6 +5130,7 @@ static PyMethodDef functions[] = { /* Utilities */ {"getcodecstatus", (PyCFunction)_getcodecstatus, METH_VARARGS}, + {"is_grayscale_palette", (PyCFunction)_is_grayscale_palette, METH_FASTCALL}, /* Special effects (experimental) */ {"effect_mandelbrot", (PyCFunction)_effect_mandelbrot, METH_VARARGS}, From 0b9c00e742078b13ad8d22d12cee9c8062fcb83c Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 22 Nov 2026 15:19:40 +1100 Subject: [PATCH 2/2] #10581 limited palette size to 256 --- Tests/test_file_bmp.py | 6 +++--- src/_imaging.c | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Tests/test_file_bmp.py b/Tests/test_file_bmp.py index 16ebc9cea5f..b9d3967f14a 100644 --- a/Tests/test_file_bmp.py +++ b/Tests/test_file_bmp.py @@ -99,7 +99,7 @@ def test_grayscale_palette_detection( assert im.convert("RGB").tobytes() == expected -@pytest.mark.parametrize("colors", (1, 2, 3, 16, 255, 257, 512)) +@pytest.mark.parametrize("colors", (1, 2, 3, 16, 255, 256)) def test_grayscale_palette_sizes(colors: int) -> None: values = (0, 255) if colors == 2 else range(colors) palette = b"".join(bytes((value & 255,)) * 3 + b"\x7f" for value in values) @@ -116,7 +116,7 @@ def test_two_color_nonidentity_palette() -> None: @pytest.mark.parametrize("padding", (3, 4)) -@pytest.mark.parametrize("colors", (1, 2, 3, 16, 256, 257)) +@pytest.mark.parametrize("colors", (1, 2, 3, 16, 256)) def test_grayscale_palette_truncation(colors: int, padding: int) -> None: values = (0, 255) if colors == 2 else range(colors) palette = b"".join( @@ -130,7 +130,7 @@ def test_grayscale_palette_truncation(colors: int, padding: int) -> None: assert not Image.core.is_grayscale_palette(b"", colors, padding) -@pytest.mark.parametrize("colors", (0, -1, 65537)) +@pytest.mark.parametrize("colors", (0, -1, 257)) def test_grayscale_palette_invalid_size(colors: int) -> None: with pytest.raises(ValueError, match="palette size"): Image.core.is_grayscale_palette(b"", colors, 4) diff --git a/src/_imaging.c b/src/_imaging.c index c83b37fdbc5..2bc5f7ba7a9 100644 --- a/src/_imaging.c +++ b/src/_imaging.c @@ -4279,8 +4279,8 @@ _is_grayscale_palette(PyObject *self, PyObject *const *args, Py_ssize_t nargs) { if (padding == -1 && PyErr_Occurred()) { return NULL; } - if (colors < 1 || colors > 65536) { - PyErr_SetString(PyExc_ValueError, "palette size must be between 1 and 65536"); + if (colors < 1 || colors > 256) { + PyErr_SetString(PyExc_ValueError, "palette size must be between 1 and 256"); return NULL; } if (padding != 3 && padding != 4) {