在 Python Flask 中通过 POST 方法发送和接收返回图像 [英] Send and receive back image by POST method in Python Flask
问题描述
我想通过 POST 方法将图像发送到服务器(例如通过 Postman),然后将相同的图像发回给用户.这是我所拥有的,我不知道如何将图像返回给用户,并给出一些响应,例如 200, .
I want to send an image by POST method to server (e.g by Postman), and then send back the same image to user. Here's what I have and i have no idea how to put image back to user with some response like 200, .
from flask import Flask, request, Response, send_file, jsonify
from PIL import Image
app = Flask(__name__)
@app.route('/')
def index():
return 'Server Works!'
@app.route('/processing', methods=['POST'])
def process():
file = request.files['image']
img = Image.open(file.stream)
return jsonify({'msg': 'success', 'size': [img.width, img.height]})
这正确获取图像并发送回一些信息,如宽度和高度,但我想要的是返回带有响应代码的相同图像.谢谢建议
This correctly get image and send back some informations like width and height, but what I want is to return the same image with response code. Thank's for suggestions
推荐答案
如果您只发送图像,那么您可以使用 send_file()
按原样发送(以字节为单位).然后浏览器就可以直接显示了.
If you would send only image then you could use send_file()
to send it as is (as bytes). And then browser could display it directly.
但是如果你想用 JSON 发送带有其他值的图像,那么你必须将它从字节转换为 base64
并添加到 JSON
But if you want to send image with other values in JSON then you have to convert it from bytes to base64
and add to JSON
data = file.stream.read()
data = base64.encodebytes(data)
return jsonify({'msg': 'success', 'size': [img.width, img.height], 'img': data})
然后您需要 JavaScript 代码将其转换回来并在浏览器中使用 canvas
显示 - 或者它使用 base64
创建 <img>
> 在网址中 -
And later you would need JavaScript code to convert it back and display using canvas
in browser - or it create <img>
using base64
in url -
对于 jpeg:
<img src="data:image/jpeg;base64,...base64 data...">
对于 png:
<img src="data:image/png;base64,...base64 data...">
所以你还必须发送信息它是什么图像 - JPG 或 PNG.
so you would have to send also information what image it is - JPG or PNG.
img.format
以 JSON 格式发送图像的最少工作代码
Minimal working code which send image in JSON
from flask import Flask, request, jsonify
from PIL import Image
import base64
app = Flask(__name__)
@app.route('/')
def index():
return '''Server Works!<hr>
<form action="/processing" method="POST" enctype="multipart/form-data">
<input type="file" name="image">
<button>OK</button>
</form>
'''
@app.route('/processing', methods=['POST'])
def process():
file = request.files['image']
img = Image.open(file.stream)
data = file.stream.read()
#data = base64.encodebytes(data)
data = base64.b64encode(data).decode()
return jsonify({
'msg': 'success',
'size': [img.width, img.height],
'format': img.format,
'img': data
})
if __name__ == '__main__':
app.run(debug=True)
如果您想在更改后发送图像(不写入磁盘),则需要使用 io.Bytes()
将对象 PIL.Image
转换为压缩文件记忆中.
If you want to send image after changes (without writing on disk) then would need to use io.Bytes()
to convert object PIL.Image
to compressed file in memory.
我还展示了如何在 HTML 中直接使用 base64 图像
I also show how to use base64 image directly in HTML
@app.route('/processing', methods=['POST'])
def process():
file = request.files['image']
img = Image.open(file.stream)
img = img.convert('L') # ie. convert to grayscale
#data = file.stream.read()
#data = base64.b64encode(data).decode()
buffer = io.BytesIO()
img.save(buffer, 'png')
buffer.seek(0)
data = buffer.read()
data = base64.b64encode(data).decode()
#return jsonify({
# 'msg': 'success',
# 'size': [img.width, img.height],
# 'format': img.format,
# 'img': data
# })
return f'<img src="data:image/png;base64,{data}">'
这篇关于在 Python Flask 中通过 POST 方法发送和接收返回图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!