flask-图片处理

1.文件方式传输图片
2.str形式传输图片

1.文件方式传输图片

html内容

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>图片识别</title>
</head>

<div style="text-align: center">
<form method="post" action="/test/ocr" enctype="multipart/form-data">
    <h3>图片识别</h3>
    <input  style="height:40px;line-height:40px;" type="file" name="image">
    <p></p>
    <input type="text" style="text-align: left" placeholder="响应格式" name="method">
    <p></p>
    <button style="margin-top: 10px" type="submit">提交</button>
</form>
</div>
</body>
</html>

flask脚本内容

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/test', methods=['POST'])
def register():

    # 获取请求体内容 image、 params、method
    image = request.files.get('image')
    url_path = request.form.get("url")
    method = request.form.get("method")
    print(image)
    print(url_path)
    print(method)
    # 保存图片
    image.save(img_path)

    return "ok"

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000, debug=True)
    

使用request发送表单 post请求

# *_*coding:utf-8
import requests

url = "服务器地址"
imag_url = "网页图片的地址"

# 发送表单post请求
# response = requests.post(url, data={"url": imag_url})

# 上传图片 files=[(变量名称,open(图片路径,rb)),()...]
response = requests.post(url, data={"method": 2}, files=[('image', open("./image/0.png", 'rb'))])

print(response.content.decode("unicode-escape"))


2.str形式传输图片

# 思路:
1. 上传图片 : 二进制方式先读取图片,然后在base64编码 ,然后在进行解码,此时类似为 str ,就可以通过json方式传输数据
2. 接收图片 : flask 获取json数据,然后解码-->再base64解码-->然后就可以二进制存图片

2.1 二进制读取图片

with open("./1.png", "rb")as f:
    content = f.read()
# 1.base64编码,再解码,此时类型由 bytes转成str,因为 json传输数据不能是bytes类型
img = base64.b64encode(content).decode()
# 2.传输数据
requests.post(url,  data=json.dumps({"Image":img}))

2.2 Flaks 获取传过来的json数据,转成字典类型

# 数据的格式为bytes,加入了as_test=True参数后就变成Unicode
data_dict = json.loads(request.get_data(as_text=True))
# 1.获取图片的值
img = new_data_dict["Image"]
with open(img_path, "wb") as f:    
    # 2.进行解码,再base64解码,就变成bytes类型
    new_image = img.encode()
    new_image = base64.b64decode(new_image)
    print(type(new_image))
    # 3.二进制方式保存图片
    f.write(new_image)

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。

文章标题:flask-图片处理

本文作者:伟生

发布时间:2022-06-19, 16:22:10

最后更新:2022-07-31, 15:48:18

原始链接:http://yoursite.com/2022/06/19/flask_02/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏