目前Android工程 APK包体积逐渐增大,从压缩图片来讲是一个解决方案,可是目前网上都没有什么好用的傻瓜式的批量压缩方案,无心中发现Pngquant能够去作这一件事,可是也只能单个文件夹压缩,没法遍历整个工程文件进行图片压缩处理。python
在这个背景下,我以为开发一个Python脚本结合Pngquant去作这件事情仍是有必要的git
github.com/RmondJone/P…github
下载源码以后,进行下面的步奏便可:数组
config.inimarkdown
[config]
#须要压缩的文件夹名称,多个以空格分隔
compressDir = drawable-hdpi drawable-xhdpi drawable-xxhdpi drawable-xxxhdpi mipmap-hdpi mipmap-xhdpi mipmap-xxhdpi mipmap-xxxhdpi
复制代码
main.pyapp
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压缩处理。oop