使用 urllib2 发送带有 flask 的图像
Send an image with flask by using urllib2
我是 Flask 的新手,我想将图像发送到客户端,该图像之前是使用 urllib2 从外部服务器接收到的。这是我向客户端发送 google 徽标的示例代码:
import urllib2
from flask import Flask, send_file
app = Flask(__name__)
@app.route('/getTestImage')
def getTestImage():
url = "https://www.google.de/images/srpr/logo11w.png"
response = urllib2.urlopen(url)
img = response.read()
response.close()
return img
if __name__ == '__main__':
app.run()
当我用浏览器(例如 Firefox)打开 127.0.0.1:5000/getTestImage
时,我只得到二进制代码。如何发送 png 文件以便浏览器显示图像?我从 Flask
中找到了 send_file
,但我真的不知道如何将该函数与从 urllib2 接收到的图像数据一起使用。
编辑: 我明白了。只需 return Response(img, mimetype="image/png")
.
您看到二进制数据是因为您直接返回图像数据。 Flask 将从视图返回的文本包装在其 default Response
object, which sets the mimetype to text/plain
中。由于您不返回纯文本数据,因此您需要创建一个描述正确 mime 类型的响应。
return app.response_class(img, mimetype='image/png')
我是 Flask 的新手,我想将图像发送到客户端,该图像之前是使用 urllib2 从外部服务器接收到的。这是我向客户端发送 google 徽标的示例代码:
import urllib2
from flask import Flask, send_file
app = Flask(__name__)
@app.route('/getTestImage')
def getTestImage():
url = "https://www.google.de/images/srpr/logo11w.png"
response = urllib2.urlopen(url)
img = response.read()
response.close()
return img
if __name__ == '__main__':
app.run()
当我用浏览器(例如 Firefox)打开 127.0.0.1:5000/getTestImage
时,我只得到二进制代码。如何发送 png 文件以便浏览器显示图像?我从 Flask
中找到了 send_file
,但我真的不知道如何将该函数与从 urllib2 接收到的图像数据一起使用。
编辑: 我明白了。只需 return Response(img, mimetype="image/png")
.
您看到二进制数据是因为您直接返回图像数据。 Flask 将从视图返回的文本包装在其 default Response
object, which sets the mimetype to text/plain
中。由于您不返回纯文本数据,因此您需要创建一个描述正确 mime 类型的响应。
return app.response_class(img, mimetype='image/png')