0

I need send image from client via request library with some json data to flask server. I found some tips but everything was either confucing or doesn't work.

I guest that it will look something like:

image = open('some_image.pgm', 'rb')
description = {"author" : "Superman", "sex" : "male"}
url = "localhost://995/image"
request = requests.post(url, file = image, data = description)

Thanks in advance for your help.

3
  • stackoverflow.com/questions/29104107/… Commented Feb 6, 2020 at 9:00
  • 2
    Does this answer your question? Upload Image using POST form data in Python-requests Commented Feb 6, 2020 at 9:01
  • it's still doesn't working, when use file, it's just return none : author= request.files['author'] -> <FileStorage: 'author' (None)>, and in this examples they just post image, but i need post image and some data Commented Feb 8, 2020 at 9:45

1 Answer 1

3

You could encode the image in a string and send it in a json like this:

import requests
import cv2
import base64
img = cv2.imread('image.jpg')
string_img = base64.b64encode(cv2.imencode('.jpg', img)[1]).decode()
req = {"author": "Superman", "sex" : "male", "image": string_img}
res = requests.post(YOUR_URL, json=req)

You can decode the image in the flask server like this:

import cv2
@app.route('/upload_image', methods=['POST'])
def upload_image():
    req = request.json
    img_str = req['image']
    #decode the image
    jpg_original = base64.b64decode(img_str)
    jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
    img = cv2.imdecode(jpg_as_np, flags=1)
    cv2.imwrite('./images.jpg', img)
Sign up to request clarification or add additional context in comments.

Comments