from pathlib import Path
from PIL import Image, ImageOps

source = Path('photos')
output = Path('web_images')
output.mkdir(exist_ok=True)
for path in sorted(source.iterdir()):
    if path.suffix.lower() not in {'.jpg', '.jpeg', '.png'}:
        continue
    target = output / (path.name + '.webp')
    if target.exists():
        print('已存在，跳过:', target)
        continue
    try:
        with Image.open(path) as image:
            if getattr(image, 'n_frames', 1) != 1:
                print('跳过多帧图片:', path)
                continue
            image = ImageOps.exif_transpose(image)
            image.thumbnail((1600, 1600))
            image = image.convert('RGBA' if 'A' in image.getbands() or 'transparency' in image.info else 'RGB')
            image.save(target, 'WEBP', quality=82, method=6)
        print(path.name, path.stat().st_size, '->', target.stat().st_size)
    except (OSError, ValueError) as exc:
        print('处理失败:', path.name, exc)
