如何使用PIL获取图像大小(字节)

Abd*_* Pp 16 python tornado filesize python-imaging-library

我发现了如何使用PIL来获取图像尺寸,而不是文件大小(以字节为单位).我需要知道文件大小来决定文件是否太大而无法上传到数据库.

the*_*orn 22

尝试:

import os
print os.stat('somefile.ext').st_size
Run Code Online (Sandbox Code Playgroud)

  • 你为什么需要使用PIL? (4认同)
  • 不,一点也不明显.PIL处理内存中的图像处理,并且它使用内部表示来有效地操纵像素.此表示可能或可能不对应于图像保存为特定格式时的大小... (3认同)

ady*_*ady 12

我认为这是内存中以字节为单位的图像大小的真正度量和最快的度量:

print("img size in memory in bytes: ", sys.getsizeof(img.tobytes()))
Run Code Online (Sandbox Code Playgroud)

然后,磁盘上文件的大小取决于文件的格式:

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)
Run Code Online (Sandbox Code Playgroud)

来自 CIFAR10 数据集的 32 x 32 x 3 图像的可能输出:

img size in memory in bytes:  3105    
img_file_size png:  2488
img_file_size jpeg:  983
Run Code Online (Sandbox Code Playgroud)


Sco*_*t A 8

如果您已在文件系统上拥有该图像:

import os
os.path.getsize('path_to_file.jpg')`
Run Code Online (Sandbox Code Playgroud)

但是,如果要获取内存中尚未保存到文件系统的图像的已保存大小:

from io import BytesIO
img_file = BytesIO()
image.save(img_file, 'png')
image_file_size = img_file.tell()
Run Code Online (Sandbox Code Playgroud)

与StringIO一样,此方法将避免多次读取图像数据.但请注意,它将使用更多RAM.一切都是权衡.:-)

编辑:我刚从OP看到这条评论:

最后,问题是来自beginnig,如果有人上传一张拥有1千兆(伪造的)的图片,他会在PIL完成它之前杀死服务器,所以我必须在它完成之前阻止请求!

这是一个非常不同的问题,可能最好在Web服务器上完成.对于nginx,您可以将其添加到您的配置中:

http {
    #...
        client_max_body_size 100m; # or whatever size you want as your limit
    #...
}
Run Code Online (Sandbox Code Playgroud)


小智 6

要使用 Pillow Library 查找图像的大小(以字节为单位),请使用以下代码。它会工作得很好。

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

确保您已安装枕头库:-

pip install pillow
Run Code Online (Sandbox Code Playgroud)

  • 如果您修改图像(例如使用调整大小)并且尚未将图像保存到磁盘,则此操作不起作用。 (2认同)

Pet*_*ter 5

我有点晚了,但是我在5分钟前遇到了这个问题,当时搜索如何获取PIL图像的大小而不将其保存到磁盘.如果有其他人遇到这个,这是一个简单的方法:

import StringIO
output = StringIO.StringIO()
image_output.save(output, 'PNG') #a format needs to be provided
contents = output.getvalue()
output.close()

image_filesize = len(contents)
Run Code Online (Sandbox Code Playgroud)