python - 获取文件的 md5 而不将其保存在光盘上

标签 python md5 python-imaging-library

我正在使用 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 程序,我们得到相同的结果结果。

关于python - 获取文件的 md5 而不将其保存在光盘上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46516277/

相关文章:

python - 如何使 tkinter 框架填充整个 Canvas 并随之扩展?

python - 在 Python 中插入主目录的问题

xcode - 如何从 SWIFT 中的字符串获取 MD5 哈希并制作桥头

javascript - 如何在 PostMan 的预请求脚本中计算 md5 哈希值?

python - Django - 没有名为 PIL 的模块

python - 我可以根据已知比例的图像计算相机姿势吗?

python - 如何通过request.user过滤django-tastypie的ToManyField?

android - 如何为 Marvel Api 请求发送时间戳和 md5 哈希

python - 在 python 中使用图像处理计算粒子

python - Pillow 已安装,但导入时出现 "no module named pillow"