PIL ValueError:图像数据不足? [英] PIL ValueError: not enough image data?

查看:529
本文介绍了PIL ValueError:图像数据不足?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试从URL提取图像并将其响应中的字符串转换为App Engine中的Image时,上述消息出现错误.

I'm getting an error with its message as above when I tried to fetch an image from a URL and converting the string in its response to Image within App Engine.

from google.appengine.api import urlfetch

def fetch_img(url):
  try:
    result = urlfetch.fetch(url=url)
    if result.status_code == 200:
      return result.content
  except Exception, e:
    logging.error(e)

url = "http://maps.googleapis.com/maps/api/staticmap?center=Narita+International+Airport,Narita,Chiba+Prefecture,+Japan&zoom=18&size=512x512&maptype=roadmap&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false"

img = fetch_img(url)
# As the URL above tells, its size is 512x512 
img = Image.fromstring('RGBA', (512, 512), img)

根据 PIL ,大小选项假设是像素元组.这是我指定的.谁能指出我的误会?

According to PIL, size option is suppose to be a tuple of pixels. This I specified. Could anyone point out my misunderstanding?

推荐答案

图像返回的数据是图像本身,而不是RAW RGB数据,因此,您无需将其作为原始数据加载,而是只需保存该原始数据即可.数据到文件,它将是一个有效的图像或使用PIL将其打开,例如(我已将您的代码转换为不使用appengine api,以便任何安装了正常python的人都可以运行xample)

The data returned by image is the image itself not the RAW RGB data, hence you don't need to load it as raw data, instead either just save that data to file and it will be a valid image or use PIL to open it e.g. (I have converted your code not to use appengine api so that anybody with normal python installation can run the xample)

from urllib2 import urlopen
import Image
import sys
import StringIO

url = "http://maps.googleapis.com/maps/api/staticmap?center=Narita+International+Airport,Narita,Chiba+Prefecture,+Japan&zoom=18&size=512x512&maptype=roadmap&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false"
result = urlopen(url=url)
if result.getcode() != 200:
  print "errrrrr"
  sys.exit(1)

imgdata = result.read()
# As the URL above tells, its size is 512x512 
img = Image.open(StringIO.StringIO(imgdata))
print img.size

输出:

(512, 512)

这篇关于PIL ValueError:图像数据不足?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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