Exercise
BMP Dimensions With Binaryreader
Objective
Develop a Python program to read the dimensions (width and height) of a BMP file using a BinaryReader-like approach.
A BMP file has a specific header structure that includes the following:
- "BM" at positions 0-1, indicating the file type.
- File size is at positions 2-5.
- Reserved space is from positions 6-7 and 8-9.
- Image data starts from positions 10-13.
- Bitmap header size is between positions 14-17.
- Width (in pixels) is located at positions 18-21.
- Height (in pixels) is located at positions 22-25.
- Planes count is at positions 26-27.
- Each point's size can be found at positions 28-29.
- Compression type (0 means no compression) is located from positions 30-33.
- Image size is at positions 34-37.
- Horizontal resolution is between positions 38-41.
- Vertical resolution is at positions 42-45.
- The size of the color table is located at positions 46-49.
Using these positions, the program must read and display the width and height of the BMP image.
Example Python Exercise
Show Python Code
# This program reads the width and height of a BMP image by parsing its header structure.
import struct
def read_bmp_dimensions(filename):
try:
# Open the BMP file in binary mode
with open(filename, 'rb') as file:
# Read the first 18 bytes to extract the relevant information
header = file.read(18)
# Check if the file is a valid BMP file by verifying "BM" signature
if header[:2] != b'BM':
print("The file is not a valid BMP file.")
return
# Extract the width and height from the header (positions 18-21 for width and 22-25 for height)
width, height = struct.unpack('
Output
Width: 800 pixels
Height: 600 pixels
Share this Python Exercise