Skip to content

Invalid 8-bit BMP files written when not all palette colours are used #6572

@ValleyBell

Description

@ValleyBell

What did you do?

I loaded an image (BMP or PNG) in 8-bit format. (i.e. with a palette of up to 256 colours)
The image did use a palette with less than 256 colours.

Then I edited the image and saved it again, as 8-bit BMP.

EDIT: This may be a similar problem as #6500.

What did you expect to happen?

The saved image should be viewable by Windows' default image viewer.

What actually happened?

The saved image was corrupt and could not be displayed.

Reason: The offset calculation for the bfSize (file offset 0x02) and bfOffBits (file offset 0x0A) assumes that the palette is 256 colours large (0x400 bytes). However there are only 0x200 bytes written for the palette. (4 bytes * 128 colours)

The fields biClrUsed (file offset 0x2E) and biClrImportant (file offset 0x32) are also incorrectly set to 256 instead of 128.

What are your OS, Python and Pillow versions?

  • OS: Windows 10 1909
  • Python: Python 3.7.6
  • Pillow: 9.2.0

I attached an archive with two tests: bmp-tests.zip

  • Test 1: BMP image with 256 colours being used (works fine)
  • Test 2: BMP image with 128 colours being used (broken after resaving)
import PIL.Image

with PIL.Image.open("Test1_AllColors.bmp") as img1:
    img1.save("t1-good.bmp")

with PIL.Image.open("Test2_128Colors.bmp") as img2:
    img2.save("t2-bad.bmp")

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions