利用Python批量压缩png方法实例(支持过滤个别文件与文件夹)

yipeiwu_com7年前Python基础

前言

本文主要给大家介绍的关于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://xiazai.jb51.net/201707/yuanma/compressImage(jb51.net).rar

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持

相关文章

python 时间信息“2018-02-04 18:23:35“ 解析成字典形式的结果代码详解

python 时间信息“2018-02-04 18:23:35“ 解析成字典形式的结果代码详解

将时间信息“2018-02-04  18:23:35“ 解析成字典形式的结果 如:{‘year':2018,‘month':2,‘day':4,‘hour':18:‘minut...

python利用re,bs4,requests模块获取股票数据

python利用re,bs4,requests模块获取股票数据

今天闲来无聊无意间看到了百度股票,就想着用python爬一下数据,于是就找到了东方财经网,结合这两个网站,写了一个小爬虫,数据保存在文件中,比较简单的示例,就当做用来练习正则表达式和Be...

opencv-python 提取sift特征并匹配的实例

我就废话不多说,直接上代码吧! # -*- coding: utf-8 -*- import cv2 import numpy as np from find_obj import...

Python实现小数转化为百分数的格式化输出方法示例

本文实例讲述了Python实现小数转化为百分数的格式化输出方法。分享给大家供大家参考,具体如下: 比如将 0.1234 转化为 12.34% 的形式: rate = .1234 pr...

Python中几种操作字符串的方法的介绍

#! -*- coding:utf-8 -*- import string s = 'Yes! This is a string' print '原字符串:'...