批量將各類圖片格式轉化爲大小更小的webp格式腳本

將待轉化格式的圖片放在一個文件夾,然後制定輸出圖片的文件夾即可

from PIL import Image
import os


def imgToWebp(input_img_path,img_width_args,img_height_args,out_img_path):
    im = Image.open(input_img_path)
    if img_width_args == 0:
        img_height = im.size[0]
        img_width = im.size[1]
    else:
        img_height = img_width_args
        img_width = img_height_args
    im.thumbnail((img_height,img_width), Image.ANTIALIAS)
    im.save(out_img_path)
    print('原圖位置:',input_img_path,'格式轉化位置:',out_img_path)


if __name__ == '__main__':


    # 支持的格式
    img_format = ['jpg', 'jpeg', 'png']
    # 輸入圖片目錄
    input_img_dir = '/Users/huangmengfeng/Desktop/待轉化圖片'
    # 輸出圖片目錄a
    out_img_dir = '/Users/huangmengfeng/Desktop/已經轉化的圖片'



    if not os.path.exists(out_img_dir):
        os.mkdir(out_img_dir)

    for child_name in os.listdir(input_img_dir):
        print(child_name)
        file_format = child_name.split('.')[-1]
        file_name_char = child_name.split('.')[0]
        if file_format in img_format:
            input_img_path_0 = os.path.join(input_img_dir,child_name)
            out_img_path_0 = os.path.join(out_img_dir,file_name_char + '.webp')
            imgToWebp(input_img_path_0,0,0,out_img_path_0)
        else:
            print(child_name,'格式不在範圍裏面',img_format)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章