PIL ValueError:图像数据不足?

问题描述 投票:0回答:4

当我尝试从 URL 获取图像并将其响应中的字符串转换为 App Engine 中的

Image
时,我收到了如上所述的错误消息。

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,大小选项应该是像素元组。这是我指定的。谁能指出我的误解吗?

python google-app-engine python-imaging-library
4个回答
7
投票

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

5
投票

fromstring
用于加载原始图像数据。字符串
img
中的内容是编码为 PNG 格式的图像。您想要做的是创建一个 StringIO 对象并让 PIL 从中读取。像这样:

>>> from StringIO import StringIO
>>> im = Image.open(StringIO(img))
>>> im
<PngImagePlugin.PngImageFile image mode=P size=512x512 at 0xC585A8>

0
投票

请注意,App Engine 不支持 PIL。它仅在开发中用作 images API 的存根。

你可以这样做:

from google.appengine.api import urlfetch
from google.appengine.api import images

class MainHandler(webapp.RequestHandler):
  def get(self):
    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 = images.Image(urlfetch.fetch(url).content)

0
投票
response = requests.get(url)
img = Image.open(BytesIO(response.content))
img.show()

它对我有用

© www.soinside.com 2019 - 2024. All rights reserved.