Python结合Pngquant给工程做图片批量压缩

454 阅读2分钟

前言

目前Android工程 APK包体积逐渐增大,从压缩图片来说是一个解决方案,但是目前网上都没有什么好用的傻瓜式的批量压缩方案,无意中发现Pngquant可以去做这一件事,但是也只能单个文件夹压缩,无法遍历整个工程文件进行图片压缩处理。

在这个背景下,我觉得开发一个Python脚本结合Pngquant去做这件事情还是有必要的

环境搭建

  • Python版本 :3.7.9,网上都有教程这里不在赘述怎么搭建
  • PyCharm IDE:直接去官网下载即可
  • Pngquant:直接去官网下载,然后加入到环境变量,在命令行可以运行pngquant -h没问题即可

Git源码

github.com/RmondJone/P…

下载源码之后,进行下面的步奏即可:

  • 第一步:config.ini 配置需要的压缩的文件夹
  • 第二步:运行main.py
  • 第三步:根据提示输入要压缩的文件夹,这里只需输入最上层目录即可,程序自动检索配置文件匹配

脚本介绍

config.ini

[config]
#需要压缩的文件夹名称,多个以空格分隔
compressDir = drawable-hdpi drawable-xhdpi drawable-xxhdpi drawable-xxxhdpi mipmap-hdpi mipmap-xhdpi mipmap-xxhdpi mipmap-xxxhdpi

main.py

import os
import threading
from config import global_config


# 压缩线程(同步压缩)
class CompressThread(threading.Thread):
    # 构造方法
    def __init__(self, compressDir) -> None:
        threading.Thread.__init__(self)
        self.compressDir = compressDir

    # 运行方法
    def run(self) -> None:
        print("线程开始运行,压缩路径为:" + self.compressDir)
        # 获得锁
        threadLock.acquire()
        cmd = "pngquant 256 --quality=65-80 --skip-if-larger --force --ext .png " + self.compressDir + "\\*.png"
        os.system(cmd)
        # 释放锁
        threadLock.release()
        print("线程结束运行,压缩路径为:" + self.compressDir)


if __name__ == '__main__':
    configDirStr = global_config.getRaw("config", "compressDir")
    configDir = configDirStr.split(" ")
    print("当前配置需要压缩的文件夹为:")
    print(configDir)
    a = """
 _____ _             _____                                     _   
|  __ (_)           |  __ \                                   | |  
| |__) |  ___ ______| |__) | __   __ _  __ _ _   _  __ _ _ __ | |_ 
|  ___/ |/ __|______|  ___/ '_ \ / _` |/ _` | | | |/ _` | '_ \| __|
| |   | | (__       | |   | | | | (_| | (_| | |_| | (_| | | | | |_ 
|_|   |_|\___|      |_|   |_| |_|\__, |\__, |\__,_|\__,_|_| |_|\__|
                                  __/ |   | |                      
                                 |___/    |_|     
                                 
请选择需要压缩的文件夹路径:                                    
"""
print(a)
dirPath = input("请输入:")
# 初始化线程锁
threadLock = threading.Lock()
# 压缩线程数组
threads = []
# 开始历遍所有子文件夹
for root, dirs, files in os.walk(dirPath):
    for dir in dirs:
        if dir in configDir:
            # 过滤编译文件夹
            if "build\generated" not in os.path.join(root, dir):
                thread = CompressThread(os.path.join(root, dir))
                threads.append(thread)
                thread.start()

# 开始遍历执行压缩线程
for thread in threads:
    thread.join()

核心代码,主要就是使用python去遍历配置文件中定义的要压缩的文件夹,然后创建同步线程执行Pngquant压缩处理。

  • --quality=65-80:压缩图片质量为65-80
  • --skip-if-larger:舍弃意义不大的压缩
  • --ext .png:这个是因为默认它会将解压缩后的Png文件重命名加后缀,这个参数即将重命名后加了一个空的字符的后缀,即等于不重命名了
  • --force:不重命名后等于要覆盖原来的文件了,这里即强制覆盖原来的文件