Exercise
Binary File Reading (BMP Example)
Objective
Develop a Python program that verifies if a BMP image file is valid by checking its header.
The program should read the file and confirm that the first two bytes match "B" and "M" (ASCII codes 0x42 and 0x4D). If they do, it indicates that the file is potentially a valid BMP image.
Example Python Exercise
Show Python Code
def verify_bmp_header(file_name):
"""
Verifies if the given file is a valid BMP image by checking its header.
Parameters:
file_name (str): The name of the file to check.
Returns:
bool: True if the file is a valid BMP, False otherwise.
"""
try:
with open(file_name, 'rb') as file:
# Read the first two bytes of the file
header = file.read(2)
# Check if the first two bytes match 'B' and 'M' (0x42 and 0x4D)
if header == b'BM':
return True
else:
return False
except FileNotFoundError:
print(f"The file '{file_name}' was not found.")
return False
except Exception as e:
print(f"An error occurred: {e}")
return False
# Main program execution
if __name__ == "__main__":
# Ask the user to input the file name
file_name = input("Please enter the BMP file name to verify: ")
# Verify if the file is a valid BMP image
if verify_bmp_header(file_name):
print(f"The file '{file_name}' is a valid BMP image.")
else:
print(f"The file '{file_name}' is not a valid BMP image.")
Output
Assume you have a BMP file named image.bmp. When you run the program, it will behave as follows:
Please enter the BMP file name to verify: image.bmp
The file 'image.bmp' is a valid BMP image.
If the file is not a BMP or the header does not match "BM", the program will output:
Please enter the BMP file name to verify: image.jpg
The file 'image.jpg' is not a valid BMP image.
If the file does not exist, it will output:
Please enter the BMP file name to verify: nonexistent.bmp
The file 'nonexistent.bmp' was not found.
Share this Python Exercise