6

From a Python Flask API, I want to return an image stream and also some text in a single API response.

Something like this:

{
  'Status' : 'Success',
  'message': message,
  'ImageBytes': imageBytes
}

Also, I would like to know what would be the best format to use for imageBytes, so that the client applications (Java / JQuery) can parse and reconstruct the image.

If the above approach is not correct, please suggest a better approach.

tuomastik
  • 4,559
  • 5
  • 36
  • 48
user1969193
  • 119
  • 1
  • 1
  • 8
  • did you try to use `{ 'Status' : 'Success', 'message': message, 'ImageBytes': imageBytes }` ? You could send image in JPG format - it should have less bytes then other formats, and some Java / JQuery should have function to display it. In flask you can use `pillow + io.BytesIO` to create JPG in memory without saving in file. – furas Aug 04 '19 at 18:02

2 Answers2

7

The following worked for me:

import io
from base64 import encodebytes
from PIL import Image
# from flask import jsonify

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

# server side code
image_path = 'images/test.png' # point to your image location
encoded_img = get_response_image(image_path)
my_message = 'here is my message' # create your message as per your need
response =  { 'Status' : 'Success', 'message': my_message , 'ImageBytes': encoded_img}
# return jsonify(response) # send the result to client
Hafizur Rahman
  • 2,314
  • 21
  • 29
2

I used the following utility function to convert the image into ByteArry and returned as one of the parameter in my JSON output.

def getImageBytes(filePath):
img = Image.open(filePath, mode='r')
imgByteArr = io.BytesIO()
imgByteArr = imgByteArr.getvalue()
imgByteArr = base64.encodebytes(imgByteArr).decode('ascii')

return imgByteArr
user1969193
  • 119
  • 1
  • 1
  • 8