Skip to main content
 首页 » 编程设计

python之PIL : How to reopen an image after verifying

2025年05月04日22kenshinobiy

我需要打开一张图片,验证图片,然后重新打开它(请参阅下面引自 PIL 文档的最后一句话)

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.

这是我的代码,其中 picture 是一个 django InMemoryUploadedFile 对象:

img = Image.open(picture) 
img.verify() 
img = Image.open(picture) 

前两行工作正常,但第三行出现以下错误(我试图“重新打开”图像):

IOError: 无法识别图像文件

按照文档的建议,重新打开图像文件的正确方法是什么?

请您参考如下方法:

这和做没有什么不同

f = open('x.png') 
Image.open(f) 
Image.open(f) 

上面的代码不起作用,因为 PIL 在读取文件的前几个字节以(尝试)识别其格式时在文件中前进。如前所述,在这种情况下尝试使用第二个 Image.open 将失败,因为现在文件中的当前位置超过了其图像的标题。要确认这一点,您可以验证 f.tell() 返回的内容。要解决此问题,您必须通过在对 Image.open 的两次调用之间执行 f.seek(0) 或关闭并重新打开文件。