"""将 /data/news/images/0622/ 中宽度超过750px的图片缩放到750px宽"""
import os, subprocess

img_dir = '/data/news/images/0622/'
resized = 0
skipped = 0

for fname in sorted(os.listdir(img_dir)):
    if not fname.lower().endswith(('.jpg', '.jpeg', '.png', '.webp')):
        continue
    fpath = os.path.join(img_dir, fname)
    
    # 获取图片尺寸
    result = subprocess.run(
        ['ffmpeg', '-i', fpath],
        capture_output=True, text=True, timeout=10
    )
    # 从stderr提取尺寸信息
    import re
    m = re.search(r'(\d+)x(\d+)', result.stderr)
    if not m:
        skipped += 1
        continue
    
    w, h = int(m.group(1)), int(m.group(2))
    if w <= 750:
        skipped += 1
        continue
    
    # 计算等比高度
    new_h = int(h * 750 / w)
    ext = fname.rsplit('.', 1)[1]
    temp_path = fpath + '.tmp.' + ext
    
    cmd = ['ffmpeg', '-y', '-i', fpath, '-vf', 'scale=%d:%d' % (750, new_h), temp_path]
    subprocess.run(cmd, capture_output=True, timeout=30)
    
    if os.path.exists(temp_path):
        os.replace(temp_path, fpath)
        resized += 1
        print('✅ %s: %dx%d → 750x%d' % (fname, w, h, new_h))

print('\n完成: %d 张已缩放, %d 张无需处理' % (resized, skipped))
