#!/usr/bin/env python3 """拖曳 .webp 檔案或資料夾到這個腳本(或用配套的 .bat), 自動轉成 iThome 可以上傳的格式(.jpg 或 .png),存到本資料夾底下的 output/(不進 git),不動原檔。 有透明背景的圖轉 .png,其餘轉 .jpg(品質 90)。 """ import sys from pathlib import Path from PIL import Image OUTPUT_DIR = Path(__file__).resolve().parent / "output" def find_webp_files(paths): files = [] for p in paths: p = Path(p) if p.is_dir(): files.extend(sorted(p.rglob("*.webp"))) elif p.is_file() and p.suffix.lower() == ".webp": files.append(p) return files def unique_path(path: Path) -> Path: if not path.exists(): return path stem, suffix = path.stem, path.suffix n = 2 while True: candidate = path.with_name(f"{stem}_{n}{suffix}") if not candidate.exists(): return candidate n += 1 def convert_one(src: Path) -> Path: img = Image.open(src) has_alpha = img.mode in ("RGBA", "LA") or ( img.mode == "P" and "transparency" in img.info ) OUTPUT_DIR.mkdir(parents=True, exist_ok=True) if has_alpha: out = unique_path(OUTPUT_DIR / src.with_suffix(".png").name) img.convert("RGBA").save(out, "PNG") else: out = unique_path(OUTPUT_DIR / src.with_suffix(".jpg").name) img.convert("RGB").save(out, "JPEG", quality=90) return out def main(): args = sys.argv[1:] if not args: print("用法:把 .webp 檔案或資料夾拖到這個腳本上(或用 拖曳轉檔.bat)") input("按 Enter 結束...") return files = find_webp_files(args) if not files: print("沒有找到 .webp 檔案。") input("按 Enter 結束...") return print(f"找到 {len(files)} 個 .webp 檔案,開始轉換...\n") for src in files: try: out = convert_one(src) print(f" OK {src.name} -> {out.name}") except Exception as e: print(f" 失敗 {src.name}: {e}") print(f"\n完成。原始 .webp 檔案沒有被動到,轉出的檔案在 {OUTPUT_DIR}") input("按 Enter 結束...") if __name__ == "__main__": main()