Python:如何从内存中的zip文件读取图像?

标签 python io buffer python-imaging-library zip

我见过这个问题的变体,但不是在这个确切的上下文中。我有一个名为 100-Test.zip 的文件,其中包含 100 个 .jpg 图像。我想在内存中打开这个文件并处理每个文件进行 PIL 操作。其余的代码已经写好了,我只想集中精力从 zip 文件获取第一个 PIL 图像。这就是我从阅读其他问题中收集的建议中代码现在的样子,但它不起作用。大家可以看一下并帮忙吗?

import zipfile
from StringIO import StringIO
from PIL import Image

imgzip = open('100-Test.zip', 'rb')
z = zipfile.ZipFile(imgzip)
data = z.read(z.namelist()[0])
dataEnc = StringIO(data)
img = Image.open(dataEnc)

print img

但是当我运行它时出现此错误:

 IOError: cannot identify image file <StringIO.StringIO instance at
 0x7f606ecffab8>

替代方案:我看到其他消息来源说可以使用这个:

image_file = StringIO(open("test.jpg",'rb').read())
im = Image.open(image_file)

但问题是我没有打开文件,它已经在数据变量的内存中。我还尝试使用 dataEnc = StringIO.read(data) 但收到此错误:

TypeError: unbound method read() must be called with StringIO instance as 
first argument (got str instance instead)

最佳答案

不需要使用StringIO。 zipfile可以读取内存中的图像文件。以下循环遍历 .zip 文件中的所有图像:

import zipfile
from PIL import Image

imgzip = zipfile.ZipFile("100-Test.zip")
inflist = imgzip.infolist()

for f in inflist:
    ifile = imgzip.open(f)
    img = Image.open(ifile)
    print(img)
    # display(img)

关于Python:如何从内存中的zip文件读取图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31777169/

相关文章:

c - char[ ] 和 char * 存在缓冲区溢出漏洞

python - 将十进制时间戳转换为日期时间时如何保留微秒?

python - 使用模板自定义 Django FormWizard 步骤

python - 在不更改 sys.path 的情况下控制 python 中的导入顺序

python - 在 Python 中使用契约式设计

java - Android - 读取文本文件时内存不足

c - 为什么要使用 shm_open?

C - 将缓冲区复制到字符串 - 这甚至可能吗?

c - 在 C 中读取文件的最快方法

java - 如何删除文件中的重复行