base64 图片进行编码、解码;api调用

1、base64 图片进行编码、解码

编码

matlab 复制代码
import base64

# 假设您有一个图像文件,例如 'image.jpg'
with open(r"C:\Users\l****1686722996428308480-1 (1).jpg", 'rb') as image_file:
    # 读取图像文件的二进制数据
    image_data = image_file.read()
    
    # 将二进制数据编码为Base64字符串
    encoded_string = base64.b64encode(image_data).decode('utf-8')
    
    print(encoded_string)

解码

matlab 复制代码
import base64
from PIL import Image
from io import BytesIO
 
# Base64 编码的字符串
base64_string = encoded_string
 
# 去除头部信息并进行解码
image_data = base64.b64decode(base64_string)
 
# 创建 BytesIO 对象来保存解码后的数据
buffered_io = BytesIO()
buffered_io.write(image_data)
 
# 打开图片文件
img = Image.open(buffered_io)
 
# 显示图片(如果需要)
img.show()

2、api调用

flask后端接口

matlab 复制代码
from flask import Flask, request

app = Flask(__name__)

@app.route('/receive-base64', methods=['POST'])
def receive_base64():
    # 从POST请求中获取Base64编码的字符串
    base64_string = request.form.get('data')
    if base64_string:
        # 这里可以添加处理Base64字符串的逻辑,例如解码或存储
        print(f"Received Base64 string: {base64_string}")
        # 返回确认消息
        return "Base64 string received successfully."
    else:
        # 如果没有接收到Base64字符串,返回错误消息
        return "No Base64 string received."

if __name__ == '__main__':
    app.run(debug=True)

requests请求

matlab 复制代码
import requests
import base64

# 假设你有一个Base64编码的字符串
base64_string = "your_base64_encoded_string_here"

# 将Base64字符串转换为字节对象
data_bytes = base64.b64decode(base64_string)

# 构建请求的payload
payload = {
    'data': data_bytes
}

# 发送POST请求
response = requests.post('http://your-flask-server-address/receive-base64', files=payload)

# 打印响应内容
print(response.text)
相关推荐
ftpeak2 小时前
从零开始使用 axum-server 构建 HTTP/HTTPS 服务
网络·http·https·rust·web·web app
weixin_4569042713 小时前
使用HTTPS 服务在浏览器端使用摄像头的方式解析
网络协议·http·https
拷贝码农卡卡东1 天前
pre-commit run --all-files 报错:http.client.RemoteDisconnected
网络·网络协议·http
又菜又爱玩呜呜呜~1 天前
go使用反射获取http.Request参数到结构体
开发语言·http·golang
cellurw1 天前
Linux下C语言实现HTTP+SQLite3电子元器件查询系统
linux·c语言·http
希望20171 天前
Golang | http/server & Gin框架简述
http·golang·gin
全栈技术负责人1 天前
前端网络性能优化实践:从 HTTP 请求到 HTTPS 与 HTTP/2 升级
前端·网络·http
Whisper_Yu1 天前
计算机网络(一)基础概念
计算机网络·http·https·信息与通信
emojiwoo2 天前
HTTP 状态码背后的逻辑:从请求到响应的完整流程解析(含完整流程图)
网络·网络协议·http
娅娅梨2 天前
HarmonyOS-ArkUI Web控件基础铺垫7-HTTP SSL认证图解 及 Charles抓包原理 及您为什么配置对了也抓不到数据
http·华为·ssl·harmonyos