开发者

md5 from pil object

how i can get md5 of the pil object without saving to file ?

    imq.sa开发者_运维百科ve('out.png')
    hash =  hashlib.md5(open('out.png','rb').read()).hexdigest()


Actually there is simpler solution:

hashlib.md5(img.tostring()).hexdigest()


Turning @Ignacio's answer into code, using this answer to help:

import StringIO, hashlib

output = StringIO.StringIO()
img.save(output)
hash = hashlib.md5(output.getvalue()).hexdigest()

As the referenced other answer notes, this might lead to a KeyError if PIL tries to automatically detect the output format. To avoid this problem you can specify the format manually:

img.save(output, format='GIF')

(Note: I've used "img" as the variable, rather than your "imq" which I assumed was a typo.)


You could write it to a StringIO instead, and then take the hash of that.


You could use the following PIL Image class method to get the raw image data to feed to md5().

im.getdata() => sequence

Returns the contents of an image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.

Note that the resulting MD5 hash of using this won't be the same as your sample code because it is (at least partially) independent of the particular image file format used to save the image. It could be useful if you wanted to compare actual images independent of the particular image file format they may be saved in.

To use it you would need to store the MD5 hash of the image data somewhere independent of any image file where it could be retrieved when needed -- as opposed to generating it by reading the entire file into memory as binary data like the code in your question does. Instead you would need to always load the image into PIL and then use the getdata() method on it to compute hashes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜