请用python和Flask帮我编写一个PNG转JPG的程序。第一步使用Python和Flask框架创建一个Web应用程序。n第二步创建一个前端HTML页面用于接收用户上传的PNG文件并显示转换结果。
以下是一个可能的解决方案:
- 安装Flask和Pillow(一个Python图像处理库):
pip install flask pillow
- 创建一个名为
app.py的Python文件,包含以下内容:
from flask import Flask, request, render_template
from PIL import Image
import io
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# 获取用户上传的文件
file = request.files['file']
# 将PNG文件转换为JPG格式
img = Image.open(file)
buffer = io.BytesIO()
img.save(buffer, format='JPEG')
buffer.seek(0)
# 返回转换后的JPG文件并在HTML页面中显示
return render_template('result.html', data=buffer.getvalue())
# 显示上传表单
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
- 创建一个名为
index.html的HTML文件,包含以下内容:
<!DOCTYPE html>
<html>
<head>
<title>PNG to JPG Converter</title>
</head>
<body>
<h1>PNG to JPG Converter</h1>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<br><br>
<button type="submit">Convert</button>
</form>
</body>
</html>
- 创建一个名为
result.html的HTML文件,包含以下内容:
<!DOCTYPE html>
<html>
<head>
<title>PNG to JPG Converter</title>
</head>
<body>
<h1>Conversion result:</h1>
<img src="data:image/jpeg;base64,{{ data|b64encode }}" alt="JPG Image">
</body>
</html>
- 运行应用程序:
python app.py
- 在浏览器中访问
http://localhost:5000,上传一个PNG文件并查看转换结果。
原文地址: https://www.cveoy.top/t/topic/gDU 著作权归作者所有。请勿转载和采集!