在Bottle中返回HTTPResponse作为图像
我刚开始使用Bottle框架,想从某个谷歌街景的链接中返回一张图片。
from bottle import run, route, redirect, request, HTTPResponse
import requests
@route('/getimage')
def getimage():
string = 'https://maps.googleapis.com/maps/api/streetview?size=400x400&location=Cleveland, Ohio'
req = requests.get(string, stream=True)
text = req.text
resp = HTTPResponse(body=text,status=400)
resp.set_header('content_type', 'image/jpeg')
return resp
run(host='localhost', port=8080, debug=True)
我不明白为什么这样做不成功——我试图创建一个HTTP响应,里面的内容是这个链接上图片的文本编码;然后我把内容类型设置为jpeg,这样就能返回一张jpeg格式的图片,但我得到的只是一个提示,告诉我图片无法显示,因为它有错误。我在Firefox和Chrome上都试过,但都不行。
如果有人能帮帮我,我会非常感激!
2 个回答
0
我刚刚测试了一下这个链接。
看起来这个链接有点问题,直接访问的时候找不到图片:
https://maps.googleapis.com/maps/api/streetview?size=400x400&location=43.20192,-83.959129
0
你需要的是 r.content
,而不是 r.text
。
来自 requests 文档:
对于非文本请求,你也可以将响应内容作为字节来访问:
> r.content b'[{"repository":{"open_issues":0,"url":"https://github.com/...
例如,要从请求返回的二进制数据中创建一张图片,你可以使用以下代码:
from PIL import Image from StringIO import StringIO i = Image.open(StringIO(r.content))