利用python和cwebp把图片转成webp格式

先安装好python3cwebp

# -*- coding: utf-8 -*-
import os
import shutil


# 输入目录的路径,注意这里是图片所在文件夹的父文件夹,末尾不带斜杠
g_path_old = '/Users/cz/Downloads/光遇雨宝'
# 图片的目录名,末尾不带斜杠
g_folder = '12'
# 可执行文件的路径,末尾不带斜杠
g_exe_path = '/Users/cz/Downloads/libwebp-1.2.1-mac-10.15/bin/cwebp'

# 统计不是png也不是jpg的文件
g_list_not_png_jpg = []
# 输出目录的路径
g_path_new = os.path.abspath('.')


# 调用可执行文件压图
def call_exe(lv_file_input, lv_file_output):
    lv_para = "%s %s %s %s"%(g_exe_path, lv_file_input, "-o", lv_file_output)
    print(lv_para)
    os.system(lv_para)

# 遍历当前目录,把所有png转换成webp
def png_2_webp(root_path_old, root_path_new):

    if os.path.isdir(root_path_new):
        shutil.rmtree(root_path_new)
    os.mkdir(root_path_new)

    for root,dirs,files in os.walk(root_path_old): 
        for dir in dirs:
            lv_dir_full_path_old = os.path.join(root,dir)
            lv_dir_full_path_new = lv_dir_full_path_old.replace(g_path_old, g_path_new)
            os.mkdir(lv_dir_full_path_new)
        for file in files:
            if file == '.DS_Store':
                continue
            lv_full_path_old = os.path.join(root,file)
            lv_list = os.path.splitext(file)
            lv_ext = lv_list[1]
            lv_file_new = lv_list[0] + '.webp'
            if lv_ext == '.PNG' or lv_ext == '.png' or lv_ext == '.JPG' or lv_ext == '.jpg' or lv_ext == '.HEIC' or lv_ext == '.heic':
                lv_full_path_new = os.path.join(root,lv_file_new)
                lv_full_path_new2 = lv_full_path_new.replace(g_path_old, g_path_new)
                call_exe(lv_full_path_old, lv_full_path_new2)
            elif lv_ext == '.MP4' or lv_ext == '.MOV':
                lv_full_path_new = lv_full_path_old.replace(g_path_old, g_path_new)
                shutil.copy(lv_full_path_old, lv_full_path_new)
            else:
                g_list_not_png_jpg.append(lv_full_path_old)
                continue

if __name__ == "__main__":
    #shutil.copytree(os.path.join(pic_floder_path, pic_floder_name), os.path.join(py_file_path, pic_floder_name))
    png_2_webp(os.path.join(g_path_old, g_folder), os.path.join(g_path_new, g_folder))
    #print(g_list_not_png_jpg)