批量将png转jpg的小脚本

写的Python脚本,复制保存,安装依赖,然后运行即可(本地要安装Python)


from PIL import Image
import os

def convert_png_to_jpg():
    # 获取当前目录下所有文件
    current_dir = os.path.dirname(os.path.abspath(__file__))
    files = os.listdir(current_dir)

    # 创建输出文件夹
    output_dir = os.path.join(current_dir, 'jpg_output')
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 遍历所有PNG文件并转换
    for file in files:
        if file.lower().endswith('.png'):
            try:
                # 打开PNG图片
                png_path = os.path.join(current_dir, file)
                image = Image.open(png_path)

                # 如果图片是RGBA模式,转换为RGB
                if image.mode == 'RGBA':
                    image = image.convert('RGB')

                # 生成输出文件路径
                jpg_filename = os.path.splitext(file)[0] + '.jpg'
                jpg_path = os.path.join(output_dir, jpg_filename)

                # 保存为JPG,质量设置为100
                image.save(jpg_path, 'JPEG', quality=100)
                print(f'已转换: {file} -> {jpg_filename}')

            except Exception as e:
                print(f'转换 {file} 时出错: {str(e)}')

if __name__ == '__main__':
    convert_png_to_jpg()