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)
相关推荐
爱吃小胖橘11 小时前
Unity网络开发--超文本传输协议Http(1)
开发语言·网络·网络协议·http·c#·游戏引擎
杰瑞学AI15 小时前
我的全栈学习之旅:FastAPI (持续更新!!!)
后端·python·websocket·学习·http·restful·fastapi
Chandler242 天前
一图掌握 网络协议 核心要点
网络协议·tcp/ip·计算机网络·http
十碗饭吃不饱3 天前
WebClient工具调用HTTP接口报错远程主机断开连接
网络·网络协议·http
失散133 天前
分布式专题——33 一台新机器进行Web页面请求的历程
分布式·tcp/ip·http·路由器·交换机
Rysxt_3 天前
Base64编码完整教程:原理、组成部分、头部解析与应用
base64
Arva .3 天前
HTTP Client
网络协议·http·lua
2501_915106324 天前
CDN 可以实现 HTTPS 吗?实战要点、部署模式与真机验证流程
网络协议·http·ios·小程序·https·uni-app·iphone
千里马-horse4 天前
HTTP、WebSocket、XMPP、CoAP、MQTT、DDS 六大协议在机器人通讯场景应用
mqtt·websocket·http·机器人·xmpp·coap·fastdds
安卓开发者4 天前
鸿蒙NEXT网络通信实战:使用HTTP协议进行网络请求
网络·http·harmonyos