优秀的编程知识分享平台

网站首页 > 技术文章 正文

Python Flask——允许用户上传图片

nanyue 2024-10-15 11:33:16 技术文章 4 ℃

假设您希望您的 Python Flask 应用程序:

  1. 允许用户上传图片
  2. 将图像传递到后端
  3. 处理图像(保存/转换/等)

这是一些允许您执行此操作的简约代码。

文件结构(仅 2 个文件)

让我们让事情尽可能简单。

templates/index.html
app.py

使用 Pip 安装所需的库

pip install flask Pillow numpy

注意:将其键入命令提示符终端。

app.py 中的代码

from flask import Flask, render_template, request
from PIL import Image
import numpy as np

app = Flask(__name__)


# 当我们以 flask 形式提交内容时,我们使用 POST 
# GET 在我们访问 localhost:5000 时发生
# POST 在我们点击时发生'upload' 
@app.route('/', methods=['GET', 'POST'])
def home():
		# 当我们访问 localhost:5000 发生
    if request.method == 'GET':
        return render_template('index.html', msg='')

		# 当我们上传图片并点击“上传”时
    image = request.files['file'] # 获取原始图像文件
    img = Image.open(image) 			# 使用 PIL 处理原始图像
    img = np.array(img) 					# 转换为 numpy 数组
		
    # 替换这里的代码,你想对图像做的任何事情
    print(img)
    print(img.shape)

    return render_template('index.html', msg='Your image has been uploaded')

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

templates/index.html 中的代码

<h3>Upload an image</h3>

<form method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    
    <br/>

    <input type="submit" value="Upload">
</form>

<h4 style="color:red">{{ msg }}</h4>

会发生什么

如果我们访问 http://localhost:5000,我们应该看到如下内容:

让我们点击“选择文件”并上传一张图片。我们应该看到:

在我们的后端,我们上传的图像被打印出来。

结论

希望这对您有所帮助!

最近发表
标签列表