flask html网页 上传图片并转存为png
时间: 2024-10-24 07:05:44 浏览: 11
在Flask框架中,结合HTML用于前端展示,可以创建一个简单的文件上传功能来处理图片,并将其转换为PNG格式。这里是一个基本步骤的概述:
1. 首先,在Flask应用中安装必要的库:
```bash
pip install Flask werkzeug Pillow
```
Werkzeug提供文件处理,Pillow则用于图像操作。
2. 创建一个路由,如`/upload`,处理图片上传:
```python
from flask import Flask, request, send_from_directory
import os
from PIL import Image
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
@app.route('/upload', methods=['POST'])
def upload_image():
if 'file' not in request.files or not allowed_file(request.files['file']):
return "Invalid file type", 400
file = request.files['file']
if file.filename == '':
return "No selected file", 400
if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.makedirs(app.config['UPLOAD_FOLDER'])
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# 图片转为PNG
img = Image.open(os.path.join(app.config['UPLOAD_FOLDER'], filename))
img.save(os.path.join(app.config['UPLOAD_FOLDER'], filename.split('.')[0] + '.png'))
return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)
if __name__ == '__main__':
app.run(debug=True)
```
在这个例子中,用户通过`<form action="/upload" method="post" enctype="multipart/form-data">`提交文件。如果文件合法,会保存原始图片并在原目录下生成其PNG版本。
阅读全文