Flask 上传图片并灰度显示
2021-11-6
·
hexWers

Flask 上传图片并灰度显示

接到了一个小需求:使用flask写上传图片并灰度显示

刚好没写过python的后端,来试一试

在这里插入图片描述

代码

使用了layui的组件

app.js

import logging
import os

from flask import Flask, render_template, request
from PIL import Image

app = Flask(__name__)

# 映射到index.html
@app.route('/')
def index():
    return render_template('index.html')

# 指定post请求
@app.route('/upload', methods=['post'])
def upload():
    # 文件不存在就退出
    if ('file' not in request.files):
        print('no found file')
        return
    img = request.files['file']

    path = os.path.abspath(os.path.dirname(__file__)) + "/static/photo"
    
	# 日志打印
    app.logger.info("path: " + path)
	# 创建文件夹
    if os.path.exists(path) == False:
        os.makedirs(path)
	
    file_path = path + "/" + img.filename
    app.logger.info('file_path: ' + file_path)
	# 保存图片
    img.save(file_path)

    img2 = Image.open(file_path)
	# 灰度变化
    Img = img2.convert('L')
    Img.save(file_path)

    fname = '/static/photo/' + img.filename

    app.logger.info(fname)

    return render_template('view.html', fpath=fname)

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

# todo 可以增加的功能,指定上传类型,生成唯一图片标识符防止图片名重复

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传</title>
    <link rel="stylesheet" href="/static/layui/css/layui.css">
    <script src="/static/layui/layui.js"></script>
    <script src="/static/js/jquery-3.6.0.js"></script>
    <style>
        body {
            text-align: center;
            padding: 20px;
        }

        form {
            width: 500px;
            margin: auto;
        }

    </style>
</head>
<body>

<form method="post" action="/upload" enctype="multipart/form-data" class="layui-form">
    <div class="layui-form-item wu-example" id="uploader" style="display: inline-block;">
        <div class="layui-input-block" >
            <input type="file" name="file"  class="layui-btn" value="添加文件"/><button class="layui-btn" lay-submit lay-filter="*">上传</button>
        </div>
    </div>
</form>

<script>

</script>

</body>
</html>

view.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片显示</title>
    <style>
        body {
            text-align: center;
            padding: 20px;
        }
    </style>
</head>
<body>
    <img src="{{ fpath }}" style="height: 300px;width: 500px" alt="pic">
</body>
</html>

部署

使用了gunicorn部署flask

在阿里云上安装pyinstaller,进行打包,然后安装gunicorn(有很多依赖组件)

将文件上传到云服务器

安装完成后输入

gunicorn  -w 2 -b :8080 app:app

这里我踩坑了,理论上gunicorn -w 2 -b 127.0.0.1:8080 app:app也是可以的,但是我那个版本好像不行,然后后面那个app:app,前面那个是你运行的文件名,后面那个是你Flask的对象,就像我app.py(前一个app)中的app = Flask(__name__)

然后正常访问即可

参考:

gunicorn文档

Flask文档