suz*_*aak 4 python google-app-engine python-imaging-library
当我尝试从 URL 获取图像并将其响应中的字符串转换为ImageApp 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)
Run Code Online (Sandbox Code Playgroud)
根据PIL, size 选项假设是一个像素元组。这是我指定的。谁能指出我的误解?
image 返回的数据是图像本身而不是 RAW RGB 数据,因此您不需要将其作为原始数据加载,而是将该数据保存到文件中,它将是一个有效的图像或使用 PIL 打开它,例如(我已将您的代码转换为不使用 appengine api,以便任何具有正常 python 安装的人都可以运行示例)
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
Run Code Online (Sandbox Code Playgroud)
输出:
(512, 512)
Run Code Online (Sandbox Code Playgroud)
fromstring用于加载原始图像数据。字符串中包含的img是编码为 PNG 格式的图像。您想要做的是创建一个StringIO对象并从中读取 PIL。像这样:
>>> from StringIO import StringIO
>>> im = Image.open(StringIO(img))
>>> im
<PngImagePlugin.PngImageFile image mode=P size=512x512 at 0xC585A8>
Run Code Online (Sandbox Code Playgroud)