2

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?

Houssem El Abed
  • 177
  • 1
  • 8

2 Answers2

10

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.

Houssem El Abed
  • 177
  • 1
  • 8
1

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

Mooncrater
  • 4,146
  • 4
  • 33
  • 62
  • thanks for this answer it's a good solution to do this, but here I can't return any other result (json result associated with the image). but it works fine. – Houssem El Abed Sep 25 '20 at 15:55