获取文件的MD5而无需在光盘上保存



我正在使用枕头编辑图像,在编辑后,我使用方法保存和下一个计数md5在保存的文件上。保存文件需要0.012,对我来说太长了。有什么方法可以在图像对象上计算MD5,而不是保存文件?

以下是使用字节对象获取文件数据的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')

输出

af521c7a78abb978fb22ddcdfb04420d

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

最新更新