当服务端接收到图像后,要保存图像到本地可以使用 Python 的 io
模块来辅助处理接收的图像数据。以下是对服务端代码的修改,使其能够接收图像并保存到本地
from flask import Flask, request
import base64
import io
from PIL import Image
app = Flask(__name__)
def process_image(image):
# 这里是图像处理的代码,你可以根据自己的需求来进行处理
# 示例代码仅为演示,需要根据实际需求进行替换
processed_image = f"Processed {image}"
return processed_image
@app.route('/process_image', methods=['POST'])
def handle_image():
if 'image' in request.form:
image_data = request.form['image']
image = base64.b64decode(image_data)
# 保存图像到本地
with Image.open(io.BytesIO(image)) as img:
img.save('received_image.jpg') # 保存为 received_image.jpg 或其他文件名
processed_image = process_image(image)
return processed_image
else:
return "No image provided."
if __name__ == '__main__':
app.run(debug=True)
Python 客户端代码
import requests
import base64
def send_image_to_server(image_path):
url = 'http://127.0.0.1:5000/process_image' # 这里替换为你的服务器地址
with open(image_path, "rb") as img_file:
encoded_string = base64.b64encode(img_file.read()).decode('utf-8')
data = {'image': encoded_string}
response = requests.post(url, data=data)
return response.text
if __name__ == '__main__':
image_path = 'path/to/your/image.jpg' # 替换为你的图像路径
result = send_image_to_server(image_path)
print("Server response:", result)
标签:__,flask,image,本地,图像,import,path,data
From: https://blog.51cto.com/u_15942288/8645586