2011-11-30 48 views
1

當我嘗試從URL獲取圖像並將其響應中的字符串轉換爲App Engine中的Image時,我收到上述消息的錯誤。PIL ValueError:沒有足夠的圖像數據?

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.&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,size選項被假設爲一個像素元組。這我指定。有誰能指出我的誤解嗎?

+0

當問一個問題,請包括整個堆棧跟蹤,而不是意譯錯誤我們。 –

回答

3

通過圖像返回的數據是圖像本身不是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.&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) 
2

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

注意PIL不支持App Engine上。它僅在dev中用作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.&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false" 
    img = images.Image(urlfetch.fetch(url).content) 
+3

Python 2.7運行時支持PIL。 – geoffspear

相關問題