PIL / urllib2 - cannot identify image file when passing file using StringIO

半世苍凉 提交于 2019-12-06 12:06:59

问题


I'm downloading an image from the web using urllib2. Once I have downloaded it I want to do some stuff with it using an image module called PIL. I don't want to save the file to disk then reopen but rather pass it from memory using StringIO

from PIL import Image

image_buff = urllib2.urlopen(url)
image = Image.open(StringIO.StringIO(image_buff))

However when I do this I get the following error

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

I think this is because I'm not passing a string but rather a urllib2 object/instance. Would anyone know how I can pass a string to PIL correctly.


回答1:


You need to .read() your urllib2.urlopen object:

import StringIO
from PIL import Image

image_buff = urllib2.urlopen(url).read()
image = Image.open(StringIO.StringIO(image_buff))



回答2:


Try this:

from PIL import image
from StringIO import StringIO

f = urllib2.urlopen("http://www.example.com/some.jpg")
data = f.read()

im = Image.open(StringIO(data))


来源:https://stackoverflow.com/questions/24615895/pil-urllib2-cannot-identify-image-file-when-passing-file-using-stringio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!