Skip to content

Instantly share code, notes, and snippets.

@bitristan
Created June 2, 2017 02:30
Show Gist options
  • Save bitristan/3ecf65724cd6df4cbdf7f5acc80f14d9 to your computer and use it in GitHub Desktop.
Save bitristan/3ecf65724cd6df4cbdf7f5acc80f14d9 to your computer and use it in GitHub Desktop.
批量递归压缩指定目录下的jpg或者png文件,使用tinify库
# -*- coding: utf-8 -*-
"""
批量递归压缩指定目录下的jpg或者png文件,使用tinify库进行压缩实现。
注意:新生成的压缩文件会替换之前的源文件,请在运行脚本之前做好备份,或者使用git之类的版本管理工具将源文件加入版本仓库!
运行脚本前需确保以下库已经安装
1. pip install tinify
2. pip install click
"""
import tinify
import os
import os.path
# 需要去 `https://tinypng.com/developers` 网站上申请api key,每个api key只能处理500张图片,可重复申请
tinify.key ="TU4CVzEfQNNqhLUvZqtfqlH0G5s1HTwJ"
fromPath ="."
for root, dirs, files in os.walk('./res'):
for name in files:
newFromFilePath = os.path.join(root, name)
fileName, fileSuffix = os.path.splitext(name)
if (fileSuffix == '.png' or fileSuffix == '.jpg'):
source = tinify.from_file(newFromFilePath)
source.to_file(newFromFilePath)
else:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment