Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 103 additions & 0 deletions Tests/test_file_bmp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, 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)
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))
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, 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)


@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
Expand Down
6 changes: 6 additions & 0 deletions docs/releasenotes/13.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
^^^^^^^^^^^^^^^^^^^^^^^^^

Expand Down
20 changes: 6 additions & 14 deletions src/PIL/BmpImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"] <= 256):
msg = f"Unsupported BMP Palette size ({file_info['colors']})"
if not (0 < colors <= 256):
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"
Expand Down
1 change: 1 addition & 0 deletions src/PIL/_imaging.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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]],
Expand Down
44 changes: 44 additions & 0 deletions src/_imaging.c
Original file line number Diff line number Diff line change
Expand Up @@ -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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Palettes are a separate concept in Pillow -- I'd name this somehow differently, since what it does is, uh... read a bytes argument that is expected to be RGB/RGBX u8 values, and checks that they're in strictly ascending order?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

all the existing comments and code call this palette? and this is also what its called in file format, I think, would it help if it said palette + "colors" or "color bytes"?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean, isn't this specific to the particular format in BMPs before it is unserialized into a Pillow palette?

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;
}
Comment on lines +4266 to +4281

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The native code in Pillow generally uses PyArg_ParseTuple() instead of doing this by hand.

if (colors < 1 || colors > 256) {
PyErr_SetString(PyExc_ValueError, "palette size must be between 1 and 256");
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;
Expand Down Expand Up @@ -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},
Expand Down
Loading