I need open an image, verify the image, then reopen it (see last sentence of below quote from PIL docs)
im.verify()
Attempts to determine if the file is broken, without actually decoding
the image data. If this method finds any problems, it raises suitable
exceptions. This method only works on a newly opened image; if the
image has already been loaded, the result is undefined. Also, if you
need to load the image after using this method, you must reopen the
image file.
This is what I have in my code, where picture is a django InMemoryUploadedFile object:
img = Image.open(picture)
img.verify()
img = Image.open(picture)
The first two lines work fine, but I get the following error for the third line (where I’m attempting to “reopen” the image):
IOError: cannot identify image file
What is the proper way to reopen the image file, as the docs suggest?
This is no different than doing
The code above does not work because PIL advances in the file while reading its first few bytes to (attempt to) identify its format. Trying to use a second
Image.openin this situation will fail as noted because now the current position in the file is past its image’s header. To confirm this, you can verify whatf.tell()returns. To solve this issue you have to go back to the start of the file either by doingf.seek(0)between the two calls toImage.open, or closing and reopening the file.