PIL/urllib2-使用StringIO传递文件时无法识别图像文件 [英] PIL / urllib2 - cannot identify image file when passing file using StringIO

查看:110
本文介绍了PIL/urllib2-使用StringIO传递文件时无法识别图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用urllib2从网络下载图像.下载完后,我想使用一个称为PIL的图像模块对它进行一些处理.我不想将文件保存到磁盘然后重新打开,而是使用StringIO

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

我认为这是因为我没有传递字符串,而是传递了urllib2对象/实例.有谁知道我如何正确地将字符串传递给PIL.

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.

推荐答案

您需要.read()您的urllib2.urlopen对象:

import StringIO
from PIL import Image

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

这篇关于PIL/urllib2-使用StringIO传递文件时无法识别图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆