import os
from PIL import Image
import shutil


def batch_webp_to_jpg(input_dir, output_dir=None):
    if not output_dir:
        output_dir = f"{os.path.dirname(input_dir)}/trans/{os.path.basename(input_dir)}"
    os.makedirs(output_dir, exist_ok=True)
    for file in os.listdir(input_dir):
        input_path = os.path.join(input_dir, file)
        if file.lower().endswith(".webp"):
            output_path = os.path.join(output_dir, file.rsplit(".", 1)[0] + ".jpg")
            with Image.open(input_path) as img:
                img.convert("RGB").save(output_path, "JPEG")
            print(f"转换完成: {output_path}")
        else:
            # 原封不动复制
            output_path = os.path.join(output_dir, file)
            shutil.copy2(input_path, output_path)
            print(f"复制完成: {output_path}")


def webp_to_jpg(input_path, output_path):
    # 打开 WebP 图片
    with Image.open(input_path) as img:
        # 转换为 RGB，因为 JPG 不支持透明通道
        rgb_img = img.convert("RGB")
        # 保存为 JPG
        rgb_img.save(output_path, "JPEG")
