我是 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/