Ejercicio
Lectura De Archivos Binarios (Ejemplo BMP)
Objectivo
Desarrollar un programa Python que verifique si un archivo de imagen BMP es válido comprobando su encabezado.
El programa debe leer el archivo y confirmar que los dos primeros bytes coinciden con "B" y "M" (códigos ASCII 0x42 y 0x4D). Si es así, indica que el archivo es potencialmente una imagen BMP válida.
Ejemplo de ejercicio de Python
Mostrar código Python
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.
Código de ejemplo copiado
Comparte este ejercicio de Python