How to get image size (bytes) using PIL

Viewed 57331

I found out how to use PIL to get the image dimensions, but not the file size in bytes. I need to know the file size to decide if the file is too big to be uploaded to the database.

5 Answers

I think this is the true measure and the fastest one of the size of the image in bytes in memory:

print("img size in memory in bytes: ", sys.getsizeof(img.tobytes()))

Then, the size of the file on disk depends on the format of the file:

from io import BytesIO
img_file = BytesIO()
img.save(img_file, 'png')
img_file_size_png = img_file.tell()
img_file = BytesIO()
img.save(img_file, 'jpeg')
img_file_size_jpeg = img_file.tell()
print("img_file_size png: ", img_file_size_png)
print("img_file_size jpeg: ", img_file_size_jpeg)

Possible output for 32 x 32 x 3 images from CIFAR10 dataset:

img size in memory in bytes:  3105    
img_file_size png:  2488
img_file_size jpeg:  983

To find the Size(In bytes) of an image using Pillow Library, please use the below code. It will working fine.

from PIL import Image
image_file = Image.open(filename)
print("File Size In Bytes:- "+str(len(image_file.fp.read()))

Make sure that you have pillow library installed:-

pip install pillow
Related