python 调用第三方库压缩png或者转换成webp

时间:2023-12-23 23:36:25

因为工作需要去研究了下png的压缩,发现转换成webp可以小很多,但是webp在手机上的解码速度比png的解码速度慢很多。出于进几年手机设备的处理器的性能也不错了,所以准备两套方案。

在网上搜索了一些资料发现了http://www.linuxfromscratch.org/blfs/view/svn/general/libwebp.html这个和https://pngquant.org/这个。

恩,我不会说了,反正第三方库的网站在这了,参数什么的自己用help看。下面是我的代码:

1.png压缩

 import os
import os.path root_path = os.getcwd()+ os.sep
exe_path = "E:\workSpace\pngTest\pngquant.exe" # full path
def check_file(file):
dic = os.path.splitext(file)
if dic[1] == ".png":
return True
return False def is_file(path):
return os.path.isfile(path) def do_common(path):
common = exe_path + " -f --quality 100 --ext .png --speed 1 " + path
print("*" * 10 + "\n" + path)
os.system(common) def walk_dir():
for root, dir_names, file_names in os.walk(root_path):
for file_name in file_names:
full_path = os.path.join(root, file_name)
if is_file(full_path):
if check_file(full_path):
do_common(full_path)
else:
walk_dir(full_path) if __name__ == "__main__":
walk_dir()

2:png转webp

 import os
import os.path root_path = os.getcwd()+ os.sep
exe_path = '''E:\workSpace\pngTest\webp\libwebp-0.3.1-windows-x64\cwebp.exe''' # full path
def check_file(file):
dic = os.path.splitext(file)
if dic[1] == ".png":
return True
return False def is_file(path):
return os.path.isfile(path) def do_common(path):
dir_name = os.path.dirname(path)
file = os.path.basename(path)
dic = os.path.splitext(file)
file_name = dic[0]
file_out_name = file_name + "_webp"
ext = dic[1]
file_out = os.path.join(dir_name, file_out_name + ".webp") common = exe_path + " -preset drawing -q 100 -alpha_q 100 -quiet " + path + " -o " + file_out
print("*" * 10 + "\n" + path)
os.system(common) os.remove(path)
print("#" * 10 + "\n" + file_out)
os.rename(file_out, path) def walk_dir():
for root, dir_names, file_names in os.walk(root_path):
for file_name in file_names:
full_path = os.path.join(root, file_name)
if is_file(full_path):
if check_file(full_path):
do_common(full_path)
else:
walk_dir(full_path) if __name__ == "__main__":
walk_dir()

如果不符合你的需求,可以自己去改代码!

转载请注明出处