我见过这个问题的变体,但不是在这个确切的上下文中。我有一个名为 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/