批量压缩项目内的图片资源
IMG_3552.jpg
1.安装pip: sudo easy_install pip
2.安装TinyPng库: sudo pip install --upgrade tinify
5.运行Python脚本 批量压缩Images.xcassets目录下的图片
Demo: Images.xcassets/Launch目录下图片进行批量压缩
效果:压缩前 1.3MB 压缩后 381KB
import tinify
import os
import os.path
import shutil
tinify.key = "xxx"
fromFilePath = "xxx/Images.xcassets"
toFilePath = "xxx"
for root, dirs, files in os.walk(fromFilePath):
for name in files:
fileName, fileSuffix = os.path.splitext(name)
toFullPath = toFilePath + root[len(fromFilePath):]
toFullName = toFullPath + '/' + name
if not os.path.exists(toFullPath):
os.makedirs(toFullPath)
if fileSuffix == '.png' or fileSuffix == '.jpg':
source = tinify.from_file(root + '/' + name)
source.to_file(toFullName)
with open(toFullName, 'rb') as source:
source_data = source.read()
result_data = tinify.from_buffer(source_data).to_buffer()
else:
if fileSuffix == '.json':
shutil.copy2(root + '/' + name, toFullName)
else:
print ("copied failed %s"%(root + '/' + name))