How to get image size (bytes) using PIL

前端 未结 5 1881
清歌不尽
清歌不尽 2020-12-18 18:20

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 d

5条回答
  •  执笔经年
    2020-12-18 19:13

    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
    

提交回复
热议问题