【问题标题】:Python PIL - open image from file object: File not open for readingPython PIL - 从文件对象打开图像:文件未打开以供读取
【发布时间】:2014-12-29 21:06:29
【问题描述】:
imgfile = open('myimage.png', 'wb')
imgfile.write(decodestring(base64_image))

f = Image.open(imgfile)

imgfile.close()

我能够将write() base64 字符串作为图像转换为imgfile。但是当我尝试用 PIL 打开这个文件时,我得到了

File not open for reading

我做错了什么?

【问题讨论】:

  • @MartijnPieters 抱歉,打错了

标签: python python-imaging-library pillow


【解决方案1】:

您打开文件是为了写入,而不是读取。您必须使用双模式,并首先倒回文件指针:

with open('myimage.png', 'w+b') as imgfile:
    imgfile.write(decodestring(base64_image))
    imgfile.seek(0)
    f = Image.open(imgfile)

这里w+表示写和读,见open() documentation

'+'
打开磁盘文件进行更新(读写)

对于二进制读写访问,'w+b' 模式打开文件并将文件截断为 0 字节。 'r+b' 打开文件而不截断。

但是,这里实际上不需要使用磁盘上的文件;改用内存文件:

from io import BytesIO

imgfile = BytesIO(decodestring(base64_image))
f = Image.open(imgfile)

【讨论】:

  • 太棒了!谢谢你。顺便说一句,我嫉妒帽子;)
【解决方案2】:

这里的问题是您正在使用wb 打开文件以进行写入,同时使用w+b 打开以进行读取。

详解in the docs here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多