|
|
import os, uuid
|
|
|
from flask import render_template, request, send_file
|
|
|
|
|
|
OUTPUT_FOLDER = os.path.join(os.path.dirname(__file__), "..", "output")
|
|
|
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
|
|
|
|
|
|
def compress_image(input_stream, quality=85):
|
|
|
"""使用 PIL 压缩图片"""
|
|
|
try:
|
|
|
from PIL import Image
|
|
|
img = Image.open(input_stream)
|
|
|
|
|
|
# 转为 RGB(支持 JPG)
|
|
|
if img.mode in ("RGBA", "P"):
|
|
|
img = img.convert("RGB")
|
|
|
|
|
|
out_name = f"compressed_{uuid.uuid4().hex}.jpg"
|
|
|
out_path = os.path.join(OUTPUT_FOLDER, out_name)
|
|
|
|
|
|
img.save(out_path, "JPEG", quality=quality, optimize=True)
|
|
|
return out_name
|
|
|
except Exception as e:
|
|
|
raise Exception(f"图片处理失败: {e}")
|
|
|
|
|
|
def page():
|
|
|
from flask import render_template, request
|
|
|
download_file = None
|
|
|
message = None
|
|
|
quality = 85
|
|
|
|
|
|
if request.method == "POST":
|
|
|
file = request.files.get("file")
|
|
|
quality = int(request.form.get("quality", 85))
|
|
|
|
|
|
if file:
|
|
|
try:
|
|
|
suffix = os.path.splitext(file.filename)[-1].lower()
|
|
|
if suffix not in [".jpg", ".jpeg", ".png", ".webp"]:
|
|
|
raise Exception("仅支持 JPG/PNG/WEBP 格式")
|
|
|
|
|
|
tmp_path = os.path.join(OUTPUT_FOLDER, f"tmp_{uuid.uuid4().hex}{suffix}")
|
|
|
file.save(tmp_path)
|
|
|
|
|
|
download_file = compress_image(tmp_path, quality)
|
|
|
os.remove(tmp_path)
|
|
|
message = "✅ 压缩成功"
|
|
|
except Exception as e:
|
|
|
message = f"❌ {e}"
|
|
|
|
|
|
return render_template("image_compress.html", download_file=download_file, message=message, quality=quality) |