diff --git a/Tests/test_file_bmp.py b/Tests/test_file_bmp.py index 3fc50ced227..fb3775d4ae7 100644 --- a/Tests/test_file_bmp.py +++ b/Tests/test_file_bmp.py @@ -69,6 +69,16 @@ def test_small_palette(tmp_path: Path) -> None: assert reloaded.getpalette() == colors +def test_empty_palette(tmp_path: Path) -> None: + im = Image.new("P", (8, 8)) + + out = tmp_path / "temp.bmp" + im.save(out) + + with Image.open(out) as reloaded: + assert_image_equal(im.convert("L"), reloaded) + + def test_save_too_large(tmp_path: Path) -> None: outfile = tmp_path / "temp.bmp" with Image.new("RGB", (1, 1)) as im: diff --git a/src/PIL/BmpImagePlugin.py b/src/PIL/BmpImagePlugin.py index 907931b926e..c3a5dc72b50 100644 --- a/src/PIL/BmpImagePlugin.py +++ b/src/PIL/BmpImagePlugin.py @@ -449,7 +449,8 @@ def _save( elif im.mode == "L": palette = b"".join(o8(i) * 3 + b"\x00" for i in range(256)) elif im.mode == "P": - palette = im.im.getpalette("RGB", "BGRX") + # Colors used should not be zero, as that is treated as the maximum + palette = im.im.getpalette("RGB", "BGRX") or b"\x00\x00\x00\x00" colors = len(palette) // 4 else: palette = None