枕头OSError:无法识别图像文件< _io.BytesIO对象,位于0x02345ED8>

时间:2014-10-01 19:44:43

标签: python pillow

我试图从http请求中获取jpeg,gif等,但我收到了错误消息。以下是代码的一部分:

def printimg(url):

    http = httppoolmgr()

    file = http.request('GET',url).read()
    r_data = binascii.unhexlify(file)
    stream = io.BytesIO(r_data)
    img = Image.open(stream)
    #img = Image.open(file)

    return img

错误代码返回:

  File "C:\Python34\lib\site-packages\pillow-2.5.3-py3.4-win32.egg\PIL\Image.py"
, line 2256, in open
OSError: cannot identify image file <_io.BytesIO object at 0x02345ED8>

有没有人遇到过这种问题?

2 个答案:

答案 0 :(得分:0)

我用以下代码替换图像的检索部分

response = requests.get(url)
img = Image.open(io.BytesIO(response.content))
img.save("picture/%s.png" % row)
self.foto = PhotoImage(file="picture/%s.png" % row)

Label(self.frame, image=self.foto, name=str(row)).grid(row=row, column=0, sticky=W)

现在关于打开图片或其他内容没有任何错误我现在遇到以下代码的其他问题:

def populate(self):

    http = httppoolmgr()
    array = xmltohash(getrack(http,'618cd2a4a2a1740a9f46e4f367ef88f3'))

    for row in range(len(array)):
        url = str((array[row]),"utf-8").split("$#$")[3]
        title = str((array[row]),"utf-8").split("$#$")[1]
        response = requests.get(url)
        img = Image.open(io.BytesIO(response.content))
        img.save("picture/%s.png" % row)
        self.foto = PhotoImage(file="picture/%s.png" % row)

        Label(self.frame, image=self.foto, name=str(row)).grid(row=row, column=0, sticky=W)
        t=str((array[row]),"utf-8").split("$#$")[1]
        Label(self.frame, text=t).grid(row=row, column=1, sticky=W)

仅显示最后一张图像,但所有文本都在框架中正确显示。如果有人可以提供帮助,我有点卡住了

此致

JRoS

答案 1 :(得分:0)

确定这个解决方案:

def populate(self):

    http = httppoolmgr()
    array = xmltohash(getrack(http,'618cd2a4a2a1740a9f46e4f367ef88f3'))

    for row in range(len(array)):
        url = str((array[row]),"utf-8").split("$#$")[3]
        title = str((array[row]),"utf-8").split("$#$")[1]
        response = requests.get(url)
        img = Image.open(io.BytesIO(response.content))
        img.save("picture/%s.png" % row)
        self.foto = PhotoImage(file="picture/%s.png" % row)

        pic=Label(self.frame, image=self.foto, name=str(row))
        pic.image = self.foto
        pic.grid(row=row, column=0, sticky=W)
        t=str((array[row]),"utf-8").split("$#$")[1]
        Label(self.frame, text=t).grid(row=row, column=1, sticky=W)

对于我的观点,没有理由为什么以前的代码不起作用但我猜python或tkinter不喜欢投出很多选项,我不知道:D