Exercise
Working With Binary GIF Files
Objective
Develop a Python program to validate the structure of a GIF image file.
The program should check if the initial four bytes are G, I, F, and 8.
If the file appears to be correct, the program should also identify the GIF version (either 87 or 89), by inspecting the byte following these four, to determine if it is a 7 or a 9.
Example Python Exercise
Show Python Code
def validate_gif(file_name):
"""
Validates the structure of a GIF file by checking the first four bytes
and identifying the GIF version (87 or 89).
Parameters:
file_name (str): The name of the GIF file to validate.
"""
try:
# Open the file in binary mode to read the first few bytes
with open(file_name, 'rb') as file:
# Read the first 6 bytes
header = file.read(6)
if len(header) < 6:
print("Error: The file is too small to be a valid GIF image.")
return
# Check if the first four bytes are 'G', 'I', 'F', and '8'
if header[:4] == b'GIF8':
# Check the 5th byte to determine the GIF version
version = header[4:5]
if version == b'7':
print("The file is a valid GIF87a image.")
elif version == b'9':
print("The file is a valid GIF89a image.")
else:
print("Error: Invalid version detected in GIF file.")
else:
print("Error: The file is not a valid GIF image (incorrect header).")
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Main program execution
if __name__ == "__main__":
file_name = input("Enter the name of the GIF file to validate (with extension, e.g., image.gif): ")
validate_gif(file_name)
Output
User Input:
Enter the name of the GIF file to validate (with extension, e.g., image.gif): example.gif
Program Output:
If the file is a valid GIF87a image:
The file is a valid GIF87a image.
If the file is a valid GIF89a image:
The file is a valid GIF89a image.
If the file has an incorrect header or version:
Error: The file is not a valid GIF image (incorrect header).
If the file is too small:
Error: The file is too small to be a valid GIF image.
Share this Python Exercise