1.到tinypng/developers注册账号,填写后在邮箱可以收到key(每个key每个月可以处理500张图片,超过后再申请一个)
2.使用python3安装tinify
sudo easy_install pip
sudo pip install --upgrade tinify
3.tiny.py文件
# -*- coding: utf-8 -*-
import os
import os.path
import tinify
tinify.key = "你申请的key"
def transformImg(file):
original_size = os.path.getsize(file) / 1000
source = tinify.from_file(file)
source.to_file(file)
size = os.path.getsize(file) / 1000
print(
f'''图片:\x1b[1;34m{file}\x1b[0m, 压缩前:\x1b[1;34m{str(original_size)}kb\x1b[0m, 压缩后:\x1b[1;34m{str(size)}kb\x1b[0m, 减少:\x1b[1;34m{str(round(original_size - size, 3))}kb\x1b[0m'''
)
def compress(path):
for dir_path, dir_names, file_names in os.walk(path):
file_names = filter(lambda file_name: (file_name[-4:] == '.jpg') | (file_name[-4:] == '.png'), file_names)
file_names = map(lambda file_name: os.path.join(dir_path, file_name), file_names)
for file in file_names:
transformImg(file)
# 超过500次后,再重新申请一个账号
print(
f'''已使用次数:\x1b[1;34m{tinify.compression_count}次\x1b[0m'''
)
if __name__ == '__main__':
compress(os.getcwd())
4.将图片放到同级目录下,然后在命令行执行
python tiny.py
网友评论