获取文件的md5而不保存在光盘上

Bar*_*cki 2 python md5 pillow

我正在使用枕头编辑图像,编辑后我使用方法保存并在保存的文件上下一次计数md5.保存文件需要0.012秒,对我来说太长了.有没有办法在Image对象上计算md5而不保存到文件?

PM *_*ing 5

下面是使用BytesIO对象获取文件数据的MD5校验和而无需将文件保存到磁盘的快速演示.

from hashlib import md5
from io import BytesIO
from PIL import Image

size = 128
filetype = 'png'

# Make a simple test image
img = Image.new('RGB', (size, size), color='red')
#img.show()

# Save it to a fake file in RAM
img_bytes = BytesIO()
img.save(img_bytes, filetype)

# Get the MD5 checksum of the fake file
md5sum = md5(img_bytes.getbuffer())
print(md5sum.hexdigest())

#If we save the data to a real file, we get the same MD5 sum on that file
#img.save('red.png')
Run Code Online (Sandbox Code Playgroud)

产量

af521c7a78abb978fb22ddcdfb04420d
Run Code Online (Sandbox Code Playgroud)

如果我们取消注释img.save('red.png')然后传递'red.png'给标准的MD5sum程序,我们会得到相同的结果.

  • @MatteoItalia 好点,但我怀疑 OP 想要完整文件数据的 MD5 哈希值。否则,他可以将原始图像数据从“Image.tobytes”(或者可能是“Image.getdata”)传递到“hashlib.md5”。 (2认同)