Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print md5 hash of an image opened with Python's PIL

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?

like image 472
ensnare Avatar asked Jun 09 '14 18:06

ensnare


2 Answers

from PIL import Image
import hashlib

md5hash = hashlib.md5(Image.open('test.png').tobytes())
print(md5hash.hexdigest())
like image 112
Vishal Avatar answered Oct 07 '22 02:10

Vishal


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.

like image 39
unutbu Avatar answered Oct 07 '22 02:10

unutbu