在Python中使用pngquant压缩png图片的教程


Posted in Python onApril 09, 2015

说到png图片压缩,可能很多人知道TinyPNG这个网站。但PS插件要钱(虽然有破解的),Developer API要连到他服务器去,不提网络传输速度,Key也是有每月限制的。
    
    但是貌似tinyPNG是使用了来自于 pngquant 的技术,至少在 http://pngquant.org/ 中是如此声称的:TinyPNG and Kraken.io — on-line interfaces for pngquant。如果真是这样,我很想对TinyPNG说呵呵。后者是开源的,连首页中提供的GUI工具也都是开源的。并且TinyPNG在首页的原理说明里面,一次都没提到pngquant

    我取了tinyPNG的首页上的示例图用pngquant命令行跑了一下,压缩率和显示效果差不多。

    pngquant首页上提供的工具中,Pngyu(http://nukesaq88.github.io/Pngyu/)是跨平台并且开源的,个人觉得已经相当好用了,直接把文件夹往里面拽就能递归处理,支持各种形式的生成方式(改名、覆盖、存储到其他目录等),压缩结束给出压缩比,并且还支持预览。

    但我还是会希望能够通过脚本来处理,一方面可定制性更强,一方面更方便整合到整个自动化的流程链中。于是我又拿出了python试图写点什么,谁知道……

    pngquant的命令行方式略坑……help中的参数说明和实际效果不一致,已经发现的问题有

    1. --force 参数无效,只要输出文件存在,就会报错,无视这个本用来指定覆写的参数
    2. --skip-if-larger 参数不正常,有时候生成文件明明比较小,也会被skip掉……

    不过好在python大法好,这些问题虽然命令行本身不能处理,但python可以在上层处理掉,下面就是目前实际使用的递归处理某文件夹png的脚本:

'''
pngquant.py
use pngquant to reduces png file size
Ruoqian, Chen<piao.polar@gmail.com> 

----------
2015/4/3
1. del option --quality=50-90, special pic need skip can config in lod ini

  lod ini format:

[PixelFormat]
map_01.png=0

  0 means skip in file

----------
2015/4/2
1. desDir can be the same to srcDir, or another dir
2. lod ini config can be not exist

----------
2015/3/31
create
'''

import os
import os.path
import sys
import ConfigParser
import string

PngquantExe="pngquant"

thisFilePath = sys.path[0];

print "this py file in dir : " + thisFilePath

projectPath = thisFilePath + "/../CMWar_2dx/CMWar_2dx/";
srcResDir = "Resources/";
dstResDir = "Resources/";

lodIniPath = projectPath + srcResDir + "ini/pic.ini"
keepOrgPaths = [];
if os.path.exists(lodIniPath):
  config = ConfigParser.SafeConfigParser()
  config.read(lodIniPath)
  section = "PixelFormat";
  options = config.options(section)
  for option in options:
    value = string.atoi(config.get(section, option))
    if not value:
      keepOrgPaths.append(option);

print keepOrgPaths

srcResPath = projectPath + srcResDir;

pngCount = 0;
transCount = 0;

#pngquant --force --skip-if-larger --ext .png --quality 50-90 --speed 1

for parent,dirnames,filenames in os.walk(srcResPath):
  print "----- process Dir " + parent
  dstDir = parent.replace(srcResDir, dstResDir)
  if not os.path.exists(dstDir):
    os.makedirs(dstDir)
  for filename in filenames:
    if os.path.splitext(filename)[1] == '.png':
      pngCount += 1;
      srcFilePath = os.path.join(parent, filename);
      dstFilePath = os.path.join(dstDir, filename);
      tmpFilePath = dstFilePath + ".tmp";

      if filename in keepOrgPaths:
        print "----- keep ----- " + filename;
      else:
#        print "----- process ----- " + filename;
#        cmd = "\"" + PngquantExe + "\"" + " --force --speed=1 --quality=50-90 -v " + srcFilePath + " -o " + tmpFilePath;
        cmd = "\"" + PngquantExe + "\"" + " --force --speed=1 " + srcFilePath + " -o " + tmpFilePath;
#        print cmd;
        os.system(cmd)
        if os.path.exists(tmpFilePath):
          sizeNew = os.path.getsize(tmpFilePath);
          sizeOld = os.path.getsize(srcFilePath);
          if sizeNew < sizeOld:
            open(dstFilePath, "wb").write(open(tmpFilePath, "rb").read())
            transCount += 1;
          os.remove(tmpFilePath)
      if not os.path.exists(dstFilePath):
        open(dstFilePath, "wb").write(open(srcFilePath, "rb").read())

print "Done. Trans Pngs: %d/%d" %(transCount, pngCount)

Python 相关文章推荐
Python+Django在windows下的开发环境配置图解
Nov 11 Python
在Python的web框架中中编写日志列表的教程
Apr 30 Python
简单掌握Python的Collections模块中counter结构的用法
Jul 07 Python
Python中强大的命令行库click入门教程
Dec 26 Python
使用Python实现windows下的抓包与解析
Jan 15 Python
Python3实现爬取简书首页文章标题和文章链接的方法【测试可用】
Dec 11 Python
python使用tkinter库实现五子棋游戏
Jun 18 Python
Python 3 判断2个字典相同
Aug 06 Python
Python函数必须先定义,后调用说明(函数调用函数例外)
Jun 02 Python
图解Python中深浅copy(通俗易懂)
Sep 03 Python
Python如何使用ElementTree解析xml
Oct 12 Python
Django路由层如何获取正确的url
Jul 15 Python
python optparse模块使用实例
Apr 09 #Python
Python中处理时间的几种方法小结
Apr 09 #Python
Python CSV模块使用实例
Apr 09 #Python
Python常用随机数与随机字符串方法实例
Apr 09 #Python
在Python中使用CasperJS获取JS渲染生成的HTML内容的教程
Apr 09 #Python
举例讲解Python程序与系统shell交互的方式
Apr 09 #Python
使用Python中的cookielib模拟登录网站
Apr 09 #Python
You might like
PHP 在5.1.* 和5.2.*之间 PDO数据库操作中的不同之处小结
2012/03/07 PHP
腾讯QQ微博API接口获取微博内容
2013/10/30 PHP
PHP调用JAVA的WebService简单实例
2014/03/11 PHP
解密ThinkPHP3.1.2版本之模块和操作映射
2014/06/19 PHP
php中 $$str 中 &quot;$$&quot; 的详解
2015/07/06 PHP
PHP正则表达式函数preg_replace用法实例分析
2020/06/04 PHP
JavaScript入门教程(7) History历史对象
2009/01/31 Javascript
基于node.js的快速开发透明代理
2010/12/25 Javascript
微信小程序 swiper制作tab切换实现附源码
2017/01/21 Javascript
微信小程序 开发之滑块视图容器(swiper)详解及实例代码
2017/02/22 Javascript
JavaScript瀑布流布局实现代码
2017/05/06 Javascript
javascript与PHP动态往类中添加方法对比
2018/03/21 Javascript
使用node打造自己的命令行工具方法教程
2018/03/26 Javascript
Vue中keep-alive组件作用详解
2020/02/04 Javascript
Bootstrap实现前端登录页面带验证码功能完整示例
2020/03/26 Javascript
vuex Module将 store 分割成模块的操作
2020/12/07 Vue.js
Python实现的Excel文件读写类
2015/07/30 Python
用Python实现斐波那契(Fibonacci)函数
2016/03/25 Python
python实现list元素按关键字相加减的方法示例
2017/06/09 Python
python八大排序算法速度实例对比
2017/12/06 Python
Python使用cx_Oracle模块操作Oracle数据库详解
2018/05/07 Python
Python快速转换numpy数组中Nan和Inf的方法实例说明
2019/02/21 Python
pyqt5 从本地选择图片 并显示在label上的实例
2019/06/13 Python
pyqt5 实现多窗口跳转的方法
2019/06/19 Python
pandas实现to_sql将DataFrame保存到数据库中
2019/07/03 Python
Python CVXOPT模块安装及使用解析
2019/08/01 Python
PyTorch 解决Dataset和Dataloader遇到的问题
2020/01/08 Python
如何在Anaconda中打开python自带idle
2020/09/21 Python
requests在python中发送请求的实例讲解
2021/02/17 Python
python 统计list中各个元素出现的次数的几种方法
2021/02/20 Python
HTML5新特性之type=file文件上传功能
2018/02/02 HTML / CSS
C#里面如何倒序排列一个数组的元素?
2013/06/21 面试题
易程科技软件测试笔试
2013/03/24 面试题
生物科学专业毕业生求职信
2014/06/02 职场文书
员工辞职信范文
2015/03/02 职场文书
实操Python爬取觅知网素材图片示例
2021/11/27 Python