以下是一个可能的解决方案:

  1. 安装Flask和Pillow(一个Python图像处理库):
pip install flask pillow
  1. 创建一个名为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)
  1. 创建一个名为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>
  1. 创建一个名为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>
  1. 运行应用程序:
python app.py
  1. 在浏览器中访问http://localhost:5000,上传一个PNG文件并查看转换结果。
请用python和Flask帮我编写一个PNG转JPG的程序。第一步使用Python和Flask框架创建一个Web应用程序。n第二步创建一个前端HTML页面用于接收用户上传的PNG文件并显示转换结果。

原文地址: https://www.cveoy.top/t/topic/gDU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录