打印使用 Python 的 PIL 打开的图像的 md5 哈希 [英] Print md5 hash of an image opened with Python's PIL

查看:55
本文介绍了打印使用 Python 的 PIL 打开的图像的 md5 哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 PIL 中打开图像,然后打印图像的 md5 哈希值而不将其保存到文件并读取文件?

How can I open an image in PIL, then print the md5 hash of the image without saving it to a file and reading the file?

推荐答案

您可以将图像保存到 io.BytesIO(),并取 md5 哈希它的价值:

You could save the image to a io.BytesIO(), and take the md5 hash of its value:

import hashlib
import Image
import io

img = Image.open(FILENAME)
m = hashlib.md5()
with io.BytesIO() as memf:
    img.save(memf, 'PNG')
    data = memf.getvalue()
    m.update(data)
print(m.hexdigest())

这将计算与将 Image 保存到文件中相同的 md5 哈希值,然后将该文件读入一个字符串并获取该字符串的 md5 哈希值:

This will compute the same md5 hash as if you saved the Image to a file, then read the file into a string and took the md5 hash of the string:

img.save(NEWFILE, 'PNG')
m = hashlib.md5()
data = open(NEWFILE, 'rb').read()
m.update(data)
print(m.hexdigest())

请注意,如果 Image 是从 JPEG 等有损格式加载的,那么您获得的 md5 哈希值可能与您从中获得的不同原始文件本身,不仅因为上面的代码将图像保存为 PNG 格式,而且因为,即使将其重新保存为 JPEG,保存为有损格式会产生不同的数据.

Note that if the Image was loaded from a lossy format such as JPEG, then the md5 hash you obtain might not be the same as the one you would obtain from the original file itself, not only because the above code saves the image in PNG format, but because, even if it were to re-save it as a JPEG, saving to a lossy format will produce different data.

这篇关于打印使用 Python 的 PIL 打开的图像的 md5 哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆