python 調用第三方庫壓縮png或者轉換成webp,pythonwebp
因為工作需要去研究了下png的壓縮,發現轉換成webp可以小很多,但是webp在手機上的解碼速度比png的解碼速度慢很多。出於進幾年手機裝置的處理器的效能也不錯了,所以準備兩套方案。
在網上搜尋了一些資料發現了http://www.linuxfromscratch.org/blfs/view/svn/general/libwebp.html這個和https://pngquant.org/這個。
恩,我不會說了,反正第三方庫的網站在這了,參數什麼的自己用help看。下面是My Code:
1.png壓縮
1 import os 2 import os.path 3 4 root_path = os.getcwd()+ os.sep 5 exe_path = "E:\workSpace\pngTest\pngquant.exe" 6 7 # full path 8 def check_file(file): 9 dic = os.path.splitext(file)10 if dic[1] == ".png":11 return True12 return False13 14 def is_file(path):15 return os.path.isfile(path)16 17 def do_common(path):18 common = exe_path + " -f --quality 100 --ext .png --speed 1 " + path19 print("*" * 10 + "\n" + path)20 os.system(common)21 22 23 def walk_dir():24 for root, dir_names, file_names in os.walk(root_path):25 for file_name in file_names:26 full_path = os.path.join(root, file_name)27 if is_file(full_path):28 if check_file(full_path):29 do_common(full_path)30 else:31 walk_dir(full_path)32 33 if __name__ == "__main__":34 walk_dir()
2:png轉webp
1 import os 2 import os.path 3 4 root_path = os.getcwd()+ os.sep 5 exe_path = '''E:\workSpace\pngTest\webp\libwebp-0.3.1-windows-x64\cwebp.exe''' 6 7 # full path 8 def check_file(file): 9 dic = os.path.splitext(file)10 if dic[1] == ".png":11 return True12 return False13 14 def is_file(path):15 return os.path.isfile(path)16 17 def do_common(path):18 dir_name = os.path.dirname(path)19 file = os.path.basename(path)20 dic = os.path.splitext(file)21 file_name = dic[0]22 file_out_name = file_name + "_webp"23 ext = dic[1]24 file_out = os.path.join(dir_name, file_out_name + ".webp")25 26 common = exe_path + " -preset drawing -q 100 -alpha_q 100 -quiet " + path + " -o " + file_out27 print("*" * 10 + "\n" + path)28 os.system(common)29 30 os.remove(path)31 print("#" * 10 + "\n" + file_out)32 os.rename(file_out, path)33 34 35 36 def walk_dir():37 for root, dir_names, file_names in os.walk(root_path):38 for file_name in file_names:39 full_path = os.path.join(root, file_name)40 if is_file(full_path):41 if check_file(full_path):42 do_common(full_path)43 else:44 walk_dir(full_path)45 46 if __name__ == "__main__":47 walk_dir()
如果不符合你的需求,可以自己去改代碼!
轉載請註明出處