|
@@ -51,6 +51,38 @@ if not config.INDEX_FILE.exists():
|
|
|
json.dump([], f, ensure_ascii=False, indent=2)
|
|
json.dump([], f, ensure_ascii=False, indent=2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+# ---------- 图片缩放辅助函数 ----------
|
|
|
|
|
+def resize_image_if_large(filepath: str, max_width: int = 1200):
|
|
|
|
|
+ """如果图片宽度超过 max_width,则等比缩放并覆盖原文件。
|
|
|
|
|
+ 不处理 GIF 文件(保留动画),若 Pillow 未安装则静默跳过。"""
|
|
|
|
|
+ try:
|
|
|
|
|
+ from PIL import Image
|
|
|
|
|
+ except ImportError:
|
|
|
|
|
+ return # 不做任何处理,避免依赖问题
|
|
|
|
|
+
|
|
|
|
|
+ try:
|
|
|
|
|
+ img = Image.open(filepath)
|
|
|
|
|
+ w, h = img.size
|
|
|
|
|
+ if w <= max_width:
|
|
|
|
|
+ return
|
|
|
|
|
+ # 跳过 GIF(避免丢失动画)
|
|
|
|
|
+ if img.format == "GIF":
|
|
|
|
|
+ return
|
|
|
|
|
+ new_h = int(h * max_width / w)
|
|
|
|
|
+ img = img.resize((max_width, new_h), Image.LANCZOS)
|
|
|
|
|
+ # 保存时尽量保留原格式和质量
|
|
|
|
|
+ save_kwargs = {}
|
|
|
|
|
+ if img.format == "JPEG":
|
|
|
|
|
+ save_kwargs["quality"] = 85
|
|
|
|
|
+ save_kwargs["optimize"] = True
|
|
|
|
|
+ elif img.format == "PNG":
|
|
|
|
|
+ save_kwargs["optimize"] = True
|
|
|
|
|
+ img.save(filepath, format=img.format, **save_kwargs)
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ # 任何异常都静默跳过,不影响上传流程
|
|
|
|
|
+ pass
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
@app.context_processor
|
|
@app.context_processor
|
|
|
def inject_user_status():
|
|
def inject_user_status():
|
|
|
"""向所有模板注入登录状态"""
|
|
"""向所有模板注入登录状态"""
|
|
@@ -180,6 +212,9 @@ def editor_upload_image():
|
|
|
file_path = editor_uploads_dir / new_name
|
|
file_path = editor_uploads_dir / new_name
|
|
|
file.save(str(file_path))
|
|
file.save(str(file_path))
|
|
|
|
|
|
|
|
|
|
+ # ---------- 对上传的图片进行缩放 ----------
|
|
|
|
|
+ resize_image_if_large(str(file_path))
|
|
|
|
|
+
|
|
|
# 生成可访问 URL 和 Markdown 片段
|
|
# 生成可访问 URL 和 Markdown 片段
|
|
|
image_url = f"/static/uploads/posts/editor_uploads/{new_name}"
|
|
image_url = f"/static/uploads/posts/editor_uploads/{new_name}"
|
|
|
markdown_code = f""
|
|
markdown_code = f""
|
|
@@ -281,7 +316,10 @@ def upload():
|
|
|
if img and img.filename:
|
|
if img and img.filename:
|
|
|
filename = secure_filename(img.filename)
|
|
filename = secure_filename(img.filename)
|
|
|
if filename:
|
|
if filename:
|
|
|
- img.save(str(upload_dir / filename))
|
|
|
|
|
|
|
+ file_path = upload_dir / filename
|
|
|
|
|
+ img.save(str(file_path))
|
|
|
|
|
+ # ---------- 对上传的图片进行缩放 ----------
|
|
|
|
|
+ resize_image_if_large(str(file_path))
|
|
|
|
|
|
|
|
# 读取 Markdown 内容
|
|
# 读取 Markdown 内容
|
|
|
with open(md_path, "r", encoding="utf-8") as f:
|
|
with open(md_path, "r", encoding="utf-8") as f:
|