Python 烧瓶返回存储在数据库中的图像
我的图像存储在MongoDB中,我想将它们返回给客户端,代码如下:Python 烧瓶返回存储在数据库中的图像,python,binary,flask,Python,Binary,Flask,我的图像存储在MongoDB中,我想将它们返回给客户端,代码如下: @app.route("/images/<int:pid>.jpg") def getImage(pid): # get image binary from MongoDB, which is bson.Binary type return image_binary @app.route(“/images/.jpg”) def getImage(pid): #从MongoDB获取图像二进制文件,它是
@app.route("/images/<int:pid>.jpg")
def getImage(pid):
# get image binary from MongoDB, which is bson.Binary type
return image_binary
@app.route(“/images/.jpg”)
def getImage(pid):
#从MongoDB获取图像二进制文件,它是bson.binary类型
返回图像\u二进制
然而,似乎我不能直接在烧瓶中返回二进制?到目前为止,我的想法是:
base64
。问题在于IE使用数据创建一个响应对象,然后设置内容类型标题。如果希望浏览器保存文件而不是显示文件,请将“内容处置”标题设置为“附件”
@app.route('/images/<int:pid>.jpg')
def get_image(pid):
image_binary = read_image(pid)
response = make_response(image_binary)
response.headers.set('Content-Type', 'image/jpeg')
response.headers.set(
'Content-Disposition', 'attachment', filename='%s.jpg' % pid)
return response
我只是想确认dav1d的第二个建议是正确的——我测试了这个(其中obj.logo是一个mongoengine ImageField),对我来说效果很好:
导入io
从flask导入当前的应用程序作为应用程序
从flask导入发送\u文件
从myproject导入Obj
@app.route('/logo.png')
def徽标():
“”“提供徽标图像。”“”
obj=obj.objects.get(title='Logo')
返回send_文件(io.BytesIO(obj.logo.read()),
附件_filename='logo.png',
mimetype='image/png')
比手动创建响应对象并设置其标题更容易。假设我随身携带存储的图像路径。下面的代码有助于通过发送图像
from flask import send_file
@app.route('/get_image')
def get_image():
filename = 'uploads\\123.jpg'
return send_file(filename, mimetype='image/jpg')
uploads是我的文件夹名,其中包含我的带有123.jpg的图像
[PS:uploads文件夹应该在脚本文件的当前目录中]
希望能有所帮助。以下内容对我很有用(对于
Python 3.7.3
):
发送后是否关闭文件对象?如果它不是BytesIO,而是某个需要调用close()的其他文件对象,谁会调用它?使用Python 3和Flask 0.12,提供二进制字符串(
b'
)可能会导致UnicodeError
send_file()
可能会更好。@Baruch使用with
子句?尽管有关于图像的问题,这里是内容类型
对于任何文件类型应用程序/octet流
如果图像在内存中该怎么办。在服务器端使用此代码,如何用javascript对其进行解码?将字符串编码为ascii,然后将字节解码为base 64并将其另存为图像?是否尝试:1。2.您好,有没有一种方法可以更新以反映js部件的显示?转换可以以一个示例图像的形式显示,该图像被读取并转换为base64格式,然后返回到原始格式使用严格的“;常数fs=要求('fs');让buff=fs.readFileSync('images/inp.png');让base64data=buff.toString('base64');log(base64data)let buffOut=新缓冲区(base64data,'base64');fs.writeFileSync('images/out.png',buffOut);log('Base64图像数据转换为文件:out.png');`现在你可以在boardkeystown找到你的角色了
from flask import send_file
@app.route('/get_image')
def get_image():
filename = 'uploads\\123.jpg'
return send_file(filename, mimetype='image/jpg')
import io
import base64
# import flask
from PIL import Image
def get_encoded_img(image_path):
img = Image.open(image_path, mode='r')
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format='PNG')
my_encoded_img = base64.encodebytes(img_byte_arr.getvalue()).decode('ascii')
return my_encoded_img
...
# your api code
...
img_path = 'assets/test.png'
img = get_encoded_img(img_path)
# prepare the response: data
response_data = {"key1": value1, "key2": value2, "image": img}
# return flask.jsonify(response_data )