我正在使用 urllib2 从 Web 下载图像。下载后,我想使用名为 PIL 的图像模块对其进行一些操作。我不想将文件保存到磁盘然后重新打开,而是使用 StringIO
from PIL import Image
image_buff = urllib2.urlopen(url)
image = Image.open(StringIO.StringIO(image_buff))
但是当我这样做时,我得到了以下错误
IOError: cannot identify image file <StringIO.StringIO instance at 0x101afa2d8
我认为这是因为我传递的不是字符串而是 urllib2 对象/实例。谁知道我如何正确地将字符串传递给 PIL。
请您参考如下方法:
你需要.read()你的urllib2.urlopen对象:
import StringIO
from PIL import Image
image_buff = urllib2.urlopen(url).read()
image = Image.open(StringIO.StringIO(image_buff))
