get md5 of file without saving it on disc

Viewed 1668

I am using pillow to edit image, after editing I use method save and next count md5 on saved file. Saving file takes 0.012s, for me is too long. Is any way to count md5 on Image object with out saving to file?

1 Answers

Here's a quick demo of using a BytesIO object to get the MD5 checksum of the file data without having to save the file to disk.

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')

output

af521c7a78abb978fb22ddcdfb04420d

If we un-comment img.save('red.png') and then pass 'red.png' to a standard MD5sum program, we get the same result.

Related