Python + Flask 传递图片

之前是用base64对图片做了下编码,当作一个参数来传递,但是这样做的话,图片太大了,不太好传,还是用post请求。

服务端

# -*- coding: utf-8 -*-
from flask import Flask, request
import base64
import numpy as np
import cv2

app = Flask(__name__)

@app.route('/image_post', methods=['POST'])
def img_post():
    if request.method == 'POST':
        # 获取图片数据
        img = request.form.get('img')
        # 把图片的二进制进行转化
        img = base64.b64decode(img.encode('ascii'))
        image_data = np.frombuffer(img, np.uint8)
        # 解码
        image_data = cv2.imdecode(image_data)
        ori_img_array = image_data
        print(type(ori_img_array))
        print('img_shape: ', ori_img_array.shape)
        # 保存
        cv2.imwrite('filename.png', image_data)
    return 'OK'

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5000)

客户端

import requests
import base64

# 本地读取图片编码进行传递
with open(r'xxx.png', 'rb') as f:
        image_bytes = base64.b64encode(f.read())
        image_bytes = image_bytes.decode('ascii')
img = image_bytes

data = {'img': img}
resp = requests.post("http://127.0.0.1:5000/image_post", data=data)

print(resp.text)
posted @   赫凯  阅读(85)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示