获取文件的 md5 而不将其保存在光盘上
get md5 of file without saving it on disc
我正在使用 pillow 编辑图像,编辑后我使用方法保存,然后对保存的文件计算 md5。保存文件需要 0.012 秒,对我来说太长了。有什么方法可以在不保存到文件的情况下计算 Image 对象上的 md5?
这是一个使用 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')
输出
af521c7a78abb978fb22ddcdfb04420d
如果我们取消注释 img.save('red.png')
然后将 'red.png'
传递给标准的 MD5sum 程序,我们会得到相同的结果。
我正在使用 pillow 编辑图像,编辑后我使用方法保存,然后对保存的文件计算 md5。保存文件需要 0.012 秒,对我来说太长了。有什么方法可以在不保存到文件的情况下计算 Image 对象上的 md5?
这是一个使用 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')
输出
af521c7a78abb978fb22ddcdfb04420d
如果我们取消注释 img.save('red.png')
然后将 'red.png'
传递给标准的 MD5sum 程序,我们会得到相同的结果。