Skip to content
Merged
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
8 changes: 3 additions & 5 deletions Tests/test_file_bmp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
7 changes: 7 additions & 0 deletions docs/releasenotes/13.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Expand Down
16 changes: 13 additions & 3 deletions src/PIL/BmpImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down Expand Up @@ -486,15 +487,24 @@ 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
+ o32(colors) # colors used
+ 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)
Expand Down
Loading