Binary Files · 6 / 14 Exercise Medium

Read dimensions of BMP image

Objective

Create a program in Python that reads the dimensions of an image in Windows bitmap (BMP) format. First check that it is a valid .bmp image by looking at the header data BM. If it is valid, get its dimensions (width x height) and display them on the screen. You can use the struct module to read the numbers from the bytes.

BMP is a Windows format that can store images of up to 24 bits (16.7 million colors). The header of a BMP image is as follows:

DescriptionBytes
Type (BM)0-1
Size2-5
Reserved6-9
Start of image data10-13
Bitmap size14-17
Width (pixels)18-21
Height (pixels)22-25
Number of planes26-27
Size of each point28-29
Compression30-33
Image size34-37
Horizontal resolution38-41
Vertical resolution42-45
Color table size46-49
Color counter50-53

Files: the file image.bmp already exists. If it starts with BM, print its dimensions in the format WIDTHxHEIGHT (for example 48x32). Otherwise print Not a valid BMP file.

Output
48x32

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise