# tiny **Repository Path**: zhoulikai/tiny ## Basic Information - **Project Name**: tiny - **Description**: tiny批量压缩 - **Primary Language**: Python - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2019-06-24 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # tiny #### 介绍 tiny批量压缩图片 #### 源代码
import os
import sys
import tinify
'''
列出所有path及其子目录下符合fileter条件的文件
'''
def list_dir(path, res, filter):
if path:
for file in os.listdir(path):
temp_dir = os.path.join(path, file)
if os.path.isdir(temp_dir):
list_dir(temp_dir, res, filter)
else:
if (file.endswith(filter) and not file.startswith(".")):
res.append(temp_dir)
return res
else:
return res
'''
使用find 命令搜索所有path及其子目录下符合fileter条件的文件
'''
def list_dir_by_shell(path, filter):
find_file_shell = 'find ' + path + ' -type f -name ' + '*' + filter
# print(find_file_shell)
output = os.popen(find_file_shell)
result = output.read()
# print(result)
return result.split()
'''
tiny 压缩
'''
def tiny(path, filter):
tinify.key = "J3ufeOH47y0x5NJVvdbBJY3DkhI7EzWZ"
res = []
list_dir(path, res, filter)
# res = list_dir_by_shell(path, filter)
if res:
tiny_dir_name = "tiny_" + os.path.basename(path) ;
tiny_dir_path = os.path.join(os.path.dirname(path), tiny_dir_name)
if not os.path.exists(tiny_dir_path):
os.makedirs(tiny_dir_path)
for file in res:
print("压缩开始" + file)
source = tinify.from_file(file)
tiny_file = os.path.join(tiny_dir_path, os.path.basename(file))
source.to_file(tiny_file)
print(file + "tiny 压缩成功:压缩后的文件为:" + tiny_file)
else:
print("没有要压缩的文件")
def main():
if len(sys.argv) <= 2:
print("请输入要压缩的目录及过滤条件")
return
path = sys.argv[1]
filter = sys.argv[2]
tiny(path, filter)
if __name__ == "__main__":
main()
#### 运行环境
1. 操作系统: Linux or Mac
2. python版本: python3以上
3. 依赖: pip install --upgrade tinify
#### 使用说明
1. python tiny.py [要压缩的文件所在的目录] [搜索的条件如只压缩png或者jpg]
2. 例如: python tiny.py /var/www/resume/img/ott jpg
3. 压缩后的文件所在目录:/var/www/resume/img/tiny_ott