【问题标题】:How to return multiple images with flask如何使用烧瓶返回多个图像
【发布时间】:2020-09-25 13:58:18
【问题描述】:

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

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

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

【问题讨论】:

    标签: python api flask python-requests endpoint


    【解决方案1】:

    解决方案是将每张图片编码为字节,将其附加到列表中,然后返回结果(来源: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 的解决方案对您有所帮助。

    【讨论】:

    • 这比我的回答要好得多。感谢您的信息!
    【解决方案2】:

    取自this answer,您可以压缩图片并发送:

    这是您使用Zip files 所需的所有代码。它会 返回一个包含所有文件的 zip 文件。

    在我的程序中,我想要压缩的所有内容都在 output 文件夹中,所以我 只需使用os.walk 并将其放入带有write 的zip 文件中。前 返回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)
    

    html我只是简单的调用路由:

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

    我希望这对某人有所帮助。 :)

    【讨论】:

    • 感谢您的回答,这是一个很好的解决方案,但在这里我无法返回任何其他结果(与图像关联的 json 结果)。但它工作正常。
    猜你喜欢
    • 2021-04-16
    • 2021-07-24
    • 2012-01-28
    • 2023-04-04
    • 2013-08-13
    • 2021-03-30
    • 1970-01-01
    • 2013-07-08
    相关资源
    最近更新 更多