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.

  • https://stackoverflow.com/questions/29104107/upload-image-using-post-form-data-in-python-requests – awakenedhaki Feb 06 '20 at 09:00
  • 2
    Does this answer your question? [Upload Image using POST form data in Python-requests](https://stackoverflow.com/questions/29104107/upload-image-using-post-form-data-in-python-requests) – awakenedhaki Feb 06 '20 at 09:01
  • it's still doesn't working, when use file, it's just return none : author= request.files['author'] -> , and in this examples they just post image, but i need post image and some data –  Feb 08 '20 at 09:45

1 Answers1

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)
Guilhem
  • 31
  • 3