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?
from PIL import Image
import hashlib
md5hash = hashlib.md5(Image.open('test.png').tobytes())
print(md5hash.hexdigest())
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())
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())
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With