如何使用 PIL/Pillow 读取 zip 文件中的图像

How to read an image inside a zip file with PIL/Pillow

我可以使用 PIL/Pillow 打开 zip 中的图像而不先将其解压缩到磁盘吗?

Python zipfile does provide a ZipFile.open() that returns a file object for a file inside the zip, and PillowImage.open() 可以获取要打开的文件对象。不幸的是,zipfile 对象没有提供 Image.open() 需要的 seek() 方法。

改为将图像文件读入RAM中的字符串(如果它不是太大),并使用StringIO获取Image.open()的文件对象:

from zipfile import ZipFile
from PIL import Image
from StringIO import StringIO

archive = ZipFile("file.zip", 'r')
image_data = archive.read("image.png")
fh = StringIO(image_data)
img = Image.open(fh)

最近的 Pillow 版本不需要 .seek():

#!/usr/bin/env python
import sys
from zipfile import ZipFile
from PIL import Image # $ pip install pillow

filename = sys.argv[1]
with ZipFile(filename) as archive:
    for entry in archive.infolist():
        with archive.open(entry) as file:
            img = Image.open(file)
            print(img.size, img.mode, len(img.getdata()))