diff --git a/Tests/test_file_bmp.py b/Tests/test_file_bmp.py index a758a4efbea..7df0c3b610d 100644 --- a/Tests/test_file_bmp.py +++ b/Tests/test_file_bmp.py @@ -20,19 +20,17 @@ from pathlib import Path -@pytest.mark.parametrize("mode", ("1", "L", "P", "RGB")) +@pytest.mark.parametrize("mode", ("1", "L", "P", "RGB", "RGBA")) def test_sanity(mode: str, tmp_path: Path) -> None: outfile = tmp_path / "temp.bmp" im = hopper(mode) - im.save(outfile, "BMP") + im.save(outfile) with Image.open(outfile) as reloaded: - reloaded.load() - assert im.mode == reloaded.mode - assert im.size == reloaded.size assert reloaded.format == "BMP" assert reloaded.get_format_mimetype() == "image/bmp" + assert_image_equal(im, reloaded) def test_invalid_file() -> None: diff --git a/docs/releasenotes/13.1.0.rst b/docs/releasenotes/13.1.0.rst index a263312fa64..1685e4c401b 100644 --- a/docs/releasenotes/13.1.0.rst +++ b/docs/releasenotes/13.1.0.rst @@ -160,6 +160,13 @@ Pillow 13.0.0 also failed to import on systems where ``libz.so.1`` was not on th default library search path, such as NixOS. Linux wheels no longer require a system zlib, and gain the speed of zlib-ng as macOS and Windows wheels already did. +BMP saving preserves alpha channel +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +RGBA images saved as BMP are now written with a BITMAPV4HEADER, bitfields +compression and channel masks, so the alpha channel is preserved when the file +is reloaded instead of being silently dropped. Other modes are unchanged. + Kerning in the basic layout engine ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/PIL/BmpImagePlugin.py b/src/PIL/BmpImagePlugin.py index cc69947ea54..6de6676a38c 100644 --- a/src/PIL/BmpImagePlugin.py +++ b/src/PIL/BmpImagePlugin.py @@ -451,7 +451,8 @@ def _save( ppm = tuple(int(x * 39.3701 + 0.5) for x in dpi) stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3) - header = 40 # or 64 for OS/2 version 2 + # Use a BITMAPV4HEADER for RGBA BMP images (not DIB) + header = 108 if im.mode == "RGBA" and bitmap_header else 40 image = stride * im.size[1] if im.mode == "1": @@ -486,7 +487,7 @@ def _save( + o32(im.size[1]) # height + o16(1) # planes + o16(bits) # depth - + o32(0) # compression (0=uncompressed) + + o32(BmpImageFile.COMPRESSIONS["BITFIELDS" if header == 108 else "RAW"]) + o32(image) # size of bitmap + o32(ppm[0]) # resolution + o32(ppm[1]) # resolution @@ -494,7 +495,16 @@ def _save( + o32(colors) # colors important ) - fp.write(b"\0" * (header - 40)) # padding (for OS/2 format) + if header == 108: + # BITMAPV4HEADER + fp.write( + o32(0x00FF0000) # red mask + + o32(0x0000FF00) # green mask + + o32(0x000000FF) # blue mask + + o32(0xFF000000) # alpha mask + + b"sRGB"[::-1] # LCS_sRGB color space + + b"\0" * 48 # endpoints and gamma + ) if palette: fp.write(palette)