当我尝试从 URL 获取图像并将其响应中的字符串转换为Image
在 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 http://www.pythonware.com/library/pil/handbook/image.htm#image-size-attribute,大小选项应该是像素元组。这是我指定的。有人能指出我的误解吗?
图像返回的数据是图像本身,而不是 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
output:
(512, 512)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)