I am a beginner and I am learning to code an image classifier. My goal is to get information about the file containing a graphic image in BMP 24 format. Display information about the image size, file size, and compare it with the size on the disk.
Code:
import os
from PIL import Image
# Get the file name from user input
file_name = input("file: ")
# Open the image file with PIL
with Image.open(file_name) as img:
# Get image information
width, height = img.size
file_size = os.path.getsize(file_name)
format_name = img.format
# Print image information
print(f"Image size: {width}x{height}")
print(f"File size: {file_size} bytes")
print(f"Format: {format_name}")
# Compare file size on disk with file size in memory
block_size = 512
disk_file_size = os.path.getsize(file_name)
memory_file_size = img.tobytes().nbytes
print("Comparing file size on disk with file size in memory:")
for i in range(0, disk_file_size, block_size):
disk_block_size = min(block_size, disk_file_size - i)
memory_block_size = min(block_size, memory_file_size - i)
if disk_block_size != memory_block_size:
print(f"Mismatch at offset {i}: disk={disk_block_size} bytes, memory={memory_block_size} bytes")
break
else:
print("File sizes on disk and in memory match.")
Error
Traceback (most recent call last):
File "C:UsersUserAppDataLocalProgramsPythonPython311Libsite-packagesPILImageFile.py", line 195, in load
read = self.load_read
^^^^^^^^^^^^^^
AttributeError: 'BmpImageFile' object has no attribute 'load_read'. Did you mean: 'load_end'?
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:UsersUserOneDriveРобочий стілprogramLAb14LabLab14_1.py", line 27, in <module>
memory_file_size = img.tobytes().nbytes
^^^^^^^^^^^^^
File "C:UsersUserAppDataLocalProgramsPythonPython311Libsite-packagesPILImage.py", line 755, in tobytes
self.load()
File "C:UsersUserAppDataLocalProgramsPythonPython311Libsite-packagesPILImageFile.py", line 199, in load
read = self.fp.read
^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'read'
Any suggestion to fix it?
I expected to get information about a file containing a graphic image in BMP 24 format. Display information about the image size, file size, and compare it with the size on the disk.
But I got only: the image size, file size and format
MorBot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.