【问题标题】:Python requests post image with json dataPython 请求使用 json 数据发布图像
【发布时间】:2023-03-23 02:00:01
【问题描述】:

我需要通过请求库将带有一些 json 数据的图像从客户端发送到烧瓶服务器。我找到了一些提示,但一切要么令人困惑,要么不起作用。

我希望它看起来像:

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

提前感谢您的帮助。

【问题讨论】:

标签: python image flask request


【解决方案1】:

您可以将图像编码为字符串并以 json 格式发送,如下所示:

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)

您可以像这样在烧瓶服务器中解码图像:

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)

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 2017-06-17
    • 2014-06-01
    • 2020-12-11
    相关资源
    最近更新 更多