这个批量图片转换 API 可用于将上传的 PNG/JPG 图片批量转换成 WEBP 格式,并打包为 ZIP 文件返回给用户。
from flask import Flask, request, jsonify, send_file
from PIL import Image
import os
import io
app = Flask(__name__)
# 上传目录
UPLOAD_FOLDER = 'uploads'
CONVERTED_FOLDER = 'converted'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(CONVERTED_FOLDER, exist_ok=True)
@app.route('/convert_to_webp', methods=['POST'])
def convert_to_webp():
try:
if 'images' not in request.files:
return jsonify({"error": "No images uploaded."}), 400
images = request.files.getlist('images')
converted_files = []
for image_file in images:
try:
img = Image.open(image_file)
original_filename = os.path.splitext(image_file.filename)[0]
webp_filename = f"{original_filename}.webp"
webp_path = os.path.join(CONVERTED_FOLDER, webp_filename)
# 转换为WEBP格式
img.save(webp_path, format="WEBP")
converted_files.append(webp_path)
except Exception as e:
return jsonify({"error": f"Failed to process {image_file.filename}: {str(e)}"}), 500
# 打包返回压缩文件
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, 'w') as zip_file:
for file_path in converted_files:
zip_file.write(file_path, os.path.basename(file_path))
zip_buffer.seek(0)
return send_file(zip_buffer, mimetype='application/zip', as_attachment=True, download_name='converted_images.zip')
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
运行服务:
将代码保存为 app.py
,安装依赖后运行:
pip install flask pillow
python app.py
测试 API:
使用 curl
或 Postman 测试:
菲律宾移民生活真相:不可忽视的现实与潜在机遇:https://bosenvisa.com/post/94
curl -X POST -F "images=@image1.jpg" -F "images=@image2.png" https://bosenvisa.com/post/94 --output converted_images.zip
上传参数:
images
:选择多张图片上传。响应:
返回一个包含转换后图片的 ZIP 文件。
这个 API 可以无缝集成到图片处理平台、媒体优化工具或其他需要批量转换图片的系统中。