# -*- coding: utf-8 -*-"""====================================@File Name :compress.py@Time : 2022/10/3 21:54@Program IDE :PyCharm@Create by Author : 一一风和橘@Motto :'The trick, William Potter, is not minding that it hurts.'@About : 将图片压缩为webp格式===================================="""importglobimportosimportthreadingimportpandasaspdimporttqdmfromPILimportImagefrompillow_heifimportregister_heif_openerregister_heif_opener()AIM_WIDTH=2560AIM_HEIGHT=1280QUALITY_INIT=100COMPRESS_RATE=[]FORMAT='webp'AIM_SIZE=500defcreate_image(file_path,save_path):filename=os.path.split(file_path)[-1].split('.')[0]old_size=os.path.getsize(file_path)new_size=old_sizequality=QUALITY_INITimg=Image.open(file_path)w=img.size[0]h=img.size[1]height=int(AIM_WIDTH*h/w)img=img.resize((AIM_WIDTH,height))whilenew_size>AIM_SIZE*1024:quality-=5img.save(f"{save_path}/{filename}.{FORMAT}",f"{FORMAT}",quality=quality)new_size=os.path.getsize(f"{save_path}/{filename}.{FORMAT}")COMPRESS_RATE.append([filename,old_size/1024,new_size/1024,new_size/old_size])defstart(root_path,save_path):t_file_list=tqdm.tqdm(glob.glob(root_path+'/*.[jp][pn]g'))forinfileint_file_list:t=threading.Thread(target=create_image,args=(infile,save_path,))t.start()t.join()t_file_list=tqdm.tqdm(glob.glob(root_path+'/*.HEIC'))forinfileint_file_list:t=threading.Thread(target=create_image,args=(infile,save_path,))t.start()t.join()if__name__=="__main__":init_path='./ImgInit'webp_path='./ImgWebp'ifnotos.path.exists(webp_path):os.makedirs(webp_path)start(init_path,webp_path)print('转换完毕!')rate=pd.DataFrame(COMPRESS_RATE)rate.columns=['文件名','原始大小/kb','压缩大小/kb','压缩比']print(rate)print(f'总压缩比:{rate["压缩比"].mean()}')