Flask Restplus返回损坏的PNG文件

时间:2018-05-17 19:34:17

标签: python flask pillow flask-restplus

使用flask_restplus使用烧瓶开发rest API。它成功返回由PIL库生成的图像文件,但该文件已损坏且无法查看。

@api.route('/annotate')
class Annotate(Resource):
        @api.representation('image/png')
        def post(self):
                file = io.BytesIO()
                img = Image.new('RGBA', (50, 50), (70, 0, 0, 255))
                img.save(file, 'png')
                file.seek(0)
                return send_file(file,
                                 as_attachment=True,
                                 attachment_filename='annotated.png',
                                 mimetype='image/png')

2 个答案:

答案 0 :(得分:0)

似乎工作得很好。我jus尝试了以下,它按预期工作。这也是最终的图像。

annotated.png

from flask import Flask, render_template, jsonify, send_file
from PIL import Image
import io
app = Flask(__name__)


@app.route('/image')
def image():
    file = io.BytesIO()
    img = Image.new('RGBA', (50, 50), (70, 0, 0, 255))
    img.save(file, 'png')
    file.seek(0)
    return send_file(
        file,
        as_attachment=True,
        attachment_filename='annotated.png',
        mimetype='image/png')

FLASK_APP=f1.py flask run一样启动它。

答案 1 :(得分:0)

请参阅此github issue

Swagger基本上搞乱了编码。如果您通过其他客户端进行呼叫,它应该可以正常工作。