Python使用pngquant实现批量压缩图片

自己写的一个批量压缩图片的小工具,文件结构如下图

使用方法:将文件夹拖到bat.bat上,即可实现对文件夹内的图片压缩。

.bat文件中的代码:

@echo off
set floder=%1%
set p_path=%~dp0
python %p_path%\reducePng.py -p %floder%
pause

python代码实现如下:

#!/usr/bin/python
# -*- coding:UTF-8 -*-

import os,os.path
import sys,getopt
import shutil

#压缩图片
def reducePic(srcFile,dstFile):
	cmd=g_curDir+'\\pngquant.exe --force --verbose --speed=1 --ordered 256 %s --output %s' %(srcFile, dstFile)
	os.system(cmd)
	

#循环递归遍历文件夹
def traverse(file_dir):
	fs = os.listdir(file_dir)
	for dir in fs:
		tmp_path = os.path.join(file_dir, dir)
		if not os.path.isdir(tmp_path):
			tu=os.path.splitext(tmp_path)
			print(tmp_path)
			if tu[1] in g_reduceFileExt:
				newPath=tmp_path.replace(g_srcPath,g_dstPath)
				print(newPath)
				reducePic(tmp_path,newPath)
		else:
			createFloder(tmp_path.replace(g_srcPath,g_dstPath))
			traverse(tmp_path)

def getFloderPath():
	opts,args=getopt.getopt(sys.argv[1:],"p:s:")
	file_path=""
	for op,value in opts:
		if op == "-p":
			file_path=value
	return file_path

def createFloder(dstpath):
	if not os.path.exists(dstpath): 
		os.mkdir(dstpath)  

def main():
	#当前路径
	global g_curDir
	g_curDir=os.path.dirname(os.path.realpath(__file__))
	
	#需要压缩的图片扩展名
	global g_reduceFileExt
	g_reduceFileExt=['.png','.jpg']
	#压缩后的图片存储目录
	global g_dstPath
	g_dstPath=g_curDir+'\\reduces'
	createFloder(g_dstPath)

	global g_srcPath
	g_srcPath=getFloderPath()
	print(g_srcPath)
	traverse(g_srcPath)

	print('files reduce success')

if __name__ == '__main__':
    main()

附:

pngquant工具官网:https://pngquant.org/

参数详情如下图:

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值