我正在使用枕头编辑图像,编辑后我使用方法保存并在保存的文件上下一次计数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')
Run Code Online (Sandbox Code Playgroud)
产量
af521c7a78abb978fb22ddcdfb04420d
Run Code Online (Sandbox Code Playgroud)
如果我们取消注释img.save('red.png')然后传递'red.png'给标准的MD5sum程序,我们会得到相同的结果.
| 归档时间: |
|
| 查看次数: |
506 次 |
| 最近记录: |