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

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

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

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

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 True
12     return False
13 
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 " + path
19     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 True
12     return False
13 
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_out
27     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()

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

转载请注明出处

posted on 2016-08-27 16:16  二二的路人甲  阅读(2469)  评论(0编辑  收藏  举报