前言

在使用TinyPng压缩图片的时候经常会遇到需要一次性压缩很多张,网站使用起来需要本地选择图片然后上传再下载压缩之后的图片,很不方便,所以想搞一个脚本在本地运行可以递归压缩文件夹及子文件夹中的所有图片。

准备工作

安装一下tinify

pip install --upgrade tinify

核心科技

import tinify
import os
import os.path

tinify.key ="XXXXXXXX" # AppKey--tinypng申请的key
fromPath ="/Users/xxx/Desktop/temp-test/pic-test/source" # source path
toPath ="/Users/xxx/Desktop/temp-test/pic-test/dest" # dest path

for root, dirs, files in os.walk(fromPath):
 newToPath = toPath
 if len(root) > len(fromPath):
  innerPath= root[len(fromPath):]
  if innerPath[0] == '/':
   innerPath = innerPath[1:]
  newToPath =  os.path.join(toPath,innerPath)

 for name in files:
  newFromFilePath = os.path.join(root, name)
  newToFilePath = os.path.join(newToPath, name)  
  fileName, fileSuffix = os.path.splitext(name)
  if fileSuffix == '.png' or fileSuffix == '.jpg':
   source = tinify.from_file(newFromFilePath)
   source.to_file(newToFilePath)
  else:
   pass

 for dirName in dirs:
  os.mkdir(os.path.join(newToPath, dirName))