Files
nanocode/image-resize/resize_auto.py
T
Ubuntu 32b43f85bd a
2026-07-03 16:58:28 +08:00

62 lines
1.6 KiB
Python

#!/usr/bin/env python3
"""自动压缩图片,无需交互"""
import os
import subprocess
from pathlib import Path
MAX_WIDTH = 2180
SOURCE_DIR = Path('/home/ubuntu/images')
BACKUP_DIR = SOURCE_DIR / 'original_backup'
def get_size(f):
try:
r = subprocess.run(['identify', '-format', '%w %h', str(f)], capture_output=True, text=True)
return map(int, r.stdout.strip().split())
except:
return None, None
def resize(f, out):
try:
cmd = ['convert', str(f), '-resize', f'{MAX_WIDTH}x>', '-quality', '90', str(out)]
subprocess.run(cmd, check=True, capture_output=True)
return True
except Exception as e:
print(f" 失败: {e}")
return False
# 创建备份目录
BACKUP_DIR.mkdir(exist_ok=True)
exts = {'.jpg', '.jpeg', '.png', '.webp'}
images = []
for f in SOURCE_DIR.iterdir():
if f.is_file() and f.suffix.lower() in exts:
w, h = get_size(f)
if w and w > MAX_WIDTH:
images.append({'file': f, 'w': w, 'h': h})
print(f"压缩 {len(images)} 张图片...\n")
success = 0
for i, item in enumerate(images, 1):
f = item['file']
print(f"[{i}/{len(images)}] {f.name}")
# 备份
backup = BACKUP_DIR / f.name
os.rename(f, backup)
# 压缩
if resize(backup, f):
nw, nh = get_size(f)
orig_kb = backup.stat().st_size / 1024
new_kb = f.stat().st_size / 1024
print(f" {item['w']}x{item['h']} → {nw}x{nh}")
print(f" {orig_kb:.1f}KB → {new_kb:.1f}KB\n")
success += 1
else:
os.rename(backup, f)
print(f"✅ 完成: {success}/{len(images)} 张")
print(f"📁 备份: {BACKUP_DIR}")