Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple images with flask

I simply create a flask endpoint that returns an image from the file system. I've done some tests with postman and it works fine. Here's the instruction that does this:

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

Now I try to send back several images at the same time, for example in my case, I try to send back each separately each face that appears in a given image. Can anyone have an idea of how to do this?

like image 770
Houssem El Abed Avatar asked Jan 22 '26 06:01

Houssem El Abed


2 Answers

The solution is to encode each picture into bytes, append it to a list, then return the result (source : How to return image stream and text as JSON response from Python Flask API ). This is the code:

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})

I hope that my solution and also the solution of @Mooncrater help.

like image 174
Houssem El Abed Avatar answered Jan 24 '26 18:01

Houssem El Abed


Taken from this answer, you can zip your images and send them:

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. :)

like image 33
Mooncrater Avatar answered Jan 24 '26 18:01

Mooncrater



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!