如何使用 Flask return 多个图像

How to return multiple images with flask

我只是创建了一个烧瓶端点,returns 来自文件系统的图像。我用邮递员做了一些测试,效果很好。 这是执行此操作的说明:

return send_file(image_path, mimetype='image/png')

现在我尝试同时发回多张图像,例如在我的情况下,我尝试分别发回给定图像中出现的每张脸。 谁能知道如何做到这一点?

摘自,您可以将图片压缩并发送:

This is all the code you need using the Zip files. It will return a zip file with all of your files.

In my program everything I want to zip is in an output folder so i just use os.walk and put it in the zip file with write. Before returning the file you need to close it, if you don't close it will return an empty file.

import zipfile
import os
from flask import send_file

@app.route('/download_all')
def download_all():
    zipf = zipfile.ZipFile('Name.zip','w', zipfile.ZIP_DEFLATED)
    for root,dirs, files in os.walk('output/'):
        for file in files:
            zipf.write('output/'+file)
    zipf.close()
    return send_file('Name.zip',
            mimetype = 'zip',
            attachment_filename= 'Name.zip',
            as_attachment = True)

In the html I simply call the route:

<a href="{{url_for( 'download_all')}}"> DOWNLOAD ALL </a>

I hope this helped somebody. :)

解决方案是将每张图片编码为字节,将其附加到列表,然后 return 结果(来源:How to return image stream and text as JSON response from Python Flask API)。这是代码:

import io
from base64 import encodebytes
from PIL import Image
from flask import jsonify
from Face_extraction import face_extraction_v2

def get_response_image(image_path):
    pil_img = Image.open(image_path, mode='r') # reads the PIL image
    byte_arr = io.BytesIO()
    pil_img.save(byte_arr, format='PNG') # convert the PIL image to byte array
    encoded_img = encodebytes(byte_arr.getvalue()).decode('ascii') # encode as base64
    return encoded_img



@app.route('/get_images',methods=['GET'])
def get_images():

    ##reuslt  contains list of path images
    result = get_images_from_local_storage()
    encoded_imges = []
    for image_path in result:
        encoded_imges.append(get_response_image(image_path))
    return jsonify({'result': encoded_imges})

我希望我的解决方案以及@Mooncrater 的解决方案有所帮助。