以前做app开发的时候,无所谓。iOS在打包的时候会自动对图片进行无损压缩。
小程序、不自动给我压缩就算了,还限制我上传包的大小。总包限制20M就算了。主包限制2M。
寄人篱下、还能说啥、干吧 ...
既然他不帮我,那我只能自己压缩了。
方案一:手动压缩。
- 优点:不要写脚本了,使劲搬砖就行。
- 缺点:1、没有办法记住哪些图片已经压缩了,无法避免重复劳动。2、伤眼睛。
方案二、写一个自动压缩脚本。
- 优点:一劳永逸
- 缺点:花时间写脚本。
综合考虑,还是写一个脚本吧。方便日后维护,后面如果有添加新的图片,直接跑一下脚本就行了。
一、准备工作。
1、注册账号。
本文使用 tinypng 网站提供的对外开放接口进行图片压缩,所以首先要在这个网站注册一个账号,并获取 API Key 官网: tinypng.com/ key 如下图 :(注意:每个key每个月可以免费压缩500张图片)

2、电脑要有python工作环境。
如果是mac电脑m1或者m2芯片,就自带的有环境了。 有没有你执行一下 ptyhon -v 或者 python3 -v 自己看一下哈 这里就不多说了,自己百度哈
3、你得有一个开发工具。
一般 python 使用 pycharm 比较多。 但是我用的 vsCode 也行。反正就写一个脚本。我所谓专不专业。
4、安装python 压缩图片依赖包
shell
pip install --upgrade tinify
二、脚本如下:
本脚本对比其他脚本、有如下好处:
- 可以遍历 sourcePath 目录下的所有图片、如果你换成你的项目路径、那就会帮你的项目路劲下的所有图片进行压缩。
- 压缩之后,会帮已经压缩过的图片记录在txt文档中。下次再跑脚本的时候会避免重复压缩。添加新图片可以直接跑脚本。之压缩新加的图片。
python
import os
import tinify
#图片所在目录
sourcePath = "**************"
# 保存已经压缩过的图片路劲
currentPath = os.getcwd()
fileName = "compressImageFile.txt"
compressTextPath = currentPath + '/' + fileName
# 遍历文件夹
def walkFile(file, imageList):
for root, dirs, files in os.walk(file):
# root 表示当前正在访问的文件夹路径
# dirs 表示该文件夹下的子目录名list
# files 表示该文件夹下的文件list
# 遍历文件
for f in files:
result = os.path.join(root, f)
if ('.png' in result) or ('.jpg' in result):
imageList.append(result)
def filterHaveCompressImg(imageList):
resultNeedCompress = []
if os.path.exists(compressTextPath):
for filePath in imageList:
haveCompress = 0
with open(compressTextPath, 'r') as file:
for line in file:
lineStr = line.strip() # 去除换行符
if lineStr == filePath:
haveCompress = 1
if haveCompress == 0:
resultNeedCompress.append(filePath)
return resultNeedCompress
else:
print('第一次压缩、创建新的txt文件')
open(compressTextPath, "w")
def compressImage(imageList):
print("一共有"+str(len(imageList))+"张图片"+"\n");
resultList = filterHaveCompressImg(imageList)
print("一共有"+str(len(resultList))+"张图片需要压缩"+"\n");
count = 0
for filePath in resultList:
print("第"+str(count)+"张图片、路径为 " + filePath)
fileDir = os.path.dirname(filePath)
fileName = os.path.basename(filePath)
unoptimizeFile = os.path.join(fileDir,fileName)
source = tinify.from_file(unoptimizeFile)
source.to_file(unoptimizeFile)
file = open(compressTextPath, 'a')
file.write(filePath + '\n')
file.close()
count = count + 1
def main():
tinify.key = "**************"
imageList = []
walkFile(sourcePath, imageList)
compressImage(imageList)
if __name__ == '__main__':
print('start ==========================================\n')
main()
print('\nend ==========================================\n')
如果你觉得有用点个赞再走吧。如果有疑问可以在下方给我留言。