Python Convert Webp To Jpg with with PIL

2024-04-28

筆記如何使用 Python PIL 將常見的 Webp 格式圖片轉換為 Jpg。

logo

說明

from PIL import Image
import glob
import os

def convert_webp_to_jpg(input_file, output_file):
    try:
        with Image.open(input_file) as img:
            if img.mode not in ['RGB', 'RGBA']:
                img = img.convert('RGB')
            img.save(output_file, 'JPEG')

    except IOError:
        print(f'Open {input_file} failed.')

os.chdir('images')
for input_image in glob.glob('*.webp'):
    output_image = input_image.replace('.webp', '.jpg')
    convert_webp_to_jpg(input_image, output_image)