Python 批量压缩png 支持过滤个别文件和文件夹

1.需求

游戏的资源大多是png图片,需要压缩,但是有些图片和文件夹里的图片,美术不想压缩,比如一些带透明度的光圈或者游戏的主要元素。所以要过滤下。发现python这个语言比较适合用在这个场景。所以写了点python.

 

 

2.源码

 

import os,sys
import os.path
rootdir=sys.path[0]

#需要过滤的文件
notActionFile = ["choose_bg1.png"]
#需要过滤的文件夹
notActionPath = ["test"]

#需要删除的文件
needDeleteFile = ["s2.png"]

def file_extension(path): 
  return os.path.splitext(path)[1] 

for parent,dirnames,filenames in os.walk(rootdir):
    for filename in filenames:
        fullPath = os.path.join(parent,filename)
        #删除文件
        for deleteFile in needDeleteFile:
           if  filename == deleteFile: 		
              os.remove(fullPath)			  
        isFilter = False
        #过滤文件压缩
        for noActionName in notActionFile:	
          if noActionName == filename:
              isFilter = True
        #过滤文件夹压缩			  
        for onePath in notActionPath:
          lastPath = fullPath.split('\\')[-2]
          if lastPath == onePath:
              isFilter = True              		   
        if file_extension(fullPath) == ".png" and isFilter == False:
          #print "action"		
          os.system("pngquant -f --ext .png --quality 50-80 \"" + fullPath  + "\"")
          print fullPath

用的是pngquant来压缩。

完整项目下载地址:

http://www.waitingfy.com/?attachment_id=1812

 

 

 

使用方法,就是复制这2个文件到需要压缩的文件夹下面,然后执行python main.py

 

http://www.waitingfy.com/wp-content/uploads/2017/05/compressImage.zip

1813

Leave a Reply

Name and Email Address are required fields.
Your email will not be published or shared with third parties.