Convert images in a compressed file such as a zip

2019-07-14 21:01发布

We could combine module zipfile.ZipFile and PIL.Image.open to read the image from the compressed file. However, we might receive an error io.UnsupportedOperation: seek after we call PIL.Image.open. It refers to the condition that I passed a ZipExtFile object to PIL.Image.open function as below:

 from zipfile import ZipFile
 from PIL import Image

 zipf = ZipFile(path, "r")

 f = zipf.open("test.jpg")

 img = Image.open(f)

So, how to fix the problem?

2条回答
Ridiculous、
2楼-- · 2019-07-14 21:08

Actually we could solve this problem by reading the content of the image and then convert it to cStringIO buffer. The code is below:

from zipfile import ZipFile
from PIL import Image

zipf = ZipFile(path, "r")

# read instead of open
content = zipf.read("test.jpg")

img = Image.open(cStringIO.StringIO(content))
查看更多
forever°为你锁心
3楼-- · 2019-07-14 21:22

In python 3.7 ZipExtFile objects now support seek operations. If you upgrade to python 3.7.2 or newer, then your code should work.

查看更多
登录 后发表回答