python - Flask,如何响应页面上的图片

标签 python flask

我是 Flask 和 Web 开发的新手,我想上传一张图片并通过我的深度学习应用程序对其进行处理,然后在页面上响应处理后的图片,这是我的框架代码

# coding: utf-8
import os
import uuid

import PIL.Image as Image
from werkzeug import secure_filename
from flask import Flask, url_for, render_template, request, url_for, redirect, send_from_directory


ALLOWED_EXTENSIONS = set(list(['png', 'jpg', 'jpeg']))
UPLOAD_FOLDER = '/tmp'
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


def process_image(file_path):
    """
    resize image to 32x32
    :param file_path: file path
    :return:
    """
    img = Image.open(file_path, mode='r')
    return img.resize([32,32], Image.ANTIALIAS)


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    _path = None
    if request.method == 'POST':
        _file = request.files['file']
        print(_file)
        if _file and allowed_file(_file.filename):
            filename = secure_filename(_file.filename)
            _path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            _file.save(_path)
            return show_pic(deep_learning(_path))

    return '''
            <!DOCTYPE html>
            <title>Web App/title>
            <h1>Deep Learning Web App</h1>
            <form action="/" method="POST" enctype="multipart/form-data">
            <input type="file" name="file" />
            <input type="submit" value="submit" />
            </form>
            '''


@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

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

如你所见,我已经实现了上传图片的函数和函数deep_learning(path),它返回处理后的图片的路径,我需要实现函数show_pic() ,我该怎么做?

最佳答案

创建 template使用您的 html 框架并将图像路径传递给 render_template() 函数。

result.html

<html>
  <img src="{{ image_path }}">
</html>

将其添加到您的 View 函数中:

return render_template('result.html', image_path=deep_learning(_path))

为此,您的文件需要位于static目录或子目录中。

关于python - Flask,如何响应页面上的图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41319715/

相关文章:

python - pip 安装 WakaDump : SyntaxError: invalid syntax at except TypeError, e

python - 将函数应用于字典的值

python - 使用 Flask 将 Pandas 数据框转换为 CSV 并提供下载服务

python - 记住聊天机器人之前的对话

python - 如何使用 **kwargs 更改默认值?

python - 如何限制可以传递给方法参数的允许值(使用类型提示允许静态代码分析)

Python heroku 为socket.io 聊天应用程序配置procfile Gunicorn + gevent |运行时错误: You need to use the gevent-websocket server

flask - Authlib客户端错误: State not equal in request and response

python - Asyncio 与另一个协程同时运行 Dash (Flask) 服务器

python / flask : only one user can call a endpoint at one time