PIL:验证后如何重新打开图像? [英] PIL: How to reopen an image after verifying?

查看:78
本文介绍了PIL:验证后如何重新打开图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need open an image, verify the image, then reopen it (see last sentence of below quote from PIL docs)

im.verify()

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对象:

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?

推荐答案

这与操作没什么不同

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

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

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.open in 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 what f.tell() returns. To solve this issue you have to go back to the start of the file either by doing f.seek(0) between the two calls to Image.open, or closing and reopening the file.

这篇关于PIL:验证后如何重新打开图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆