1

I wan't to send an image from android to python jupyter notebook using url i.e HTTPpost as json object . I have flask code where that imaage will be predicted and return the label of that image, I also want to send the result back to android.

I have tried to encode image first in bitmap then into byte array and send it as string json object. But i don't know how to receive that image in python

python file:

    from flask import Flask
    from flask import request

    app = Flask(__name__)

    @app.route('/')
    def index():

        return "Welcome to Contact Less PALM Authentication"

    @app.route('/authenticate',methods = ['POST', 'GET'])
    def authenticate():
        #image_name = request.args.get('image_name')
        json_string=request.get_json()
        print("JSON String "+str(json_string))

        #path = test_path + "/"+image_name
        #img= image.load_img(path, target_size=image_size)
        #x = image.img_to_array(img)

        return "JSON String "+str(json_string) #+ predict_label(x)

        if __name__ == '__main__':
        app.run(host='0.0.0.0')

Android code:

    private JSONObject buidJsonObject() throws JSONException {

            JSONObject jsonObject = new JSONObject();
                    Bitmap bitmap =((BitmapDrawable)user_img.getDrawable()).getBitmap();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageInByte = baos.toByteArray();
            String img_array = Base64.encodeToString(imageInByte, Base64.DEFAULT);
           // String img_array = new String(imageInByte);
            try {
                baos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            jsonObject.accumulate("image_Array",img_array);

            return jsonObject;
        }
Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
MahnoorS.
  • 19
  • 1
  • 2

1 Answers1

0

Send the image in your Android code

After encoding the image, send it via a POST request. I don't know java precisely, but you can look at this answer.

Receive the image in your Flask server

After receiving the post request, use the function decode('base64') from the library base64. Then, you can save the image on your server for instance.

The base64 string contains only the content of the file, not the metadata. If you want the filename on the server, you have to send it via an other parameter.

import base64

@app.route('/authenticate',methods = ['POST', 'GET'])
def authenticate():
    encodedImg = request.form['file'] # 'file' is the name of the parameter you used to send the image

    imgdata = base64.b64decode(encodedImg)

    filename = 'image.jpg'  # choose a filename. You can send it via the request in an other variable
    with open(filename, 'wb') as f:
        f.write(imgdata)
XavierBrt
  • 1,179
  • 8
  • 13