图片批量压缩工具—tinify
admin 于 2022年02月26日 发表在 Python软件开发
访问官网,地址:https://tinypng.com/developers/reference/python


2. 调用接口
以笔者目录为例,10月份图片内容如下:

使用Python调用tinify接口,实现目录下的图片批量压缩。具体代码如下:
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 23 16:21:03 2021
@author: Administrator
"""
import os
import tinify
# 安装库 : pip install tinify
# 填写自己的API_KEY
# 官网直接输入自己邮箱便可以获取,地址:https://tinypng.com/developers
# 每个月有500张免费压缩次数
tinify.key = "xxxxxxxxxxxxxxxxxxxxxxxxxXTd40cx"
# 设置遍历路径
path = "./图片/"
# 压缩后的图片是否覆盖原有图片,0-不覆盖(会新建目录_res);1-覆盖
USE_COVER_ORIGIN_FIGURE = 1
# 得到文件名称
def list_dir(path):
list_name = []
for file in os.listdir(path):
file_path = os.path.join(path, file)
list_name.append(file_path)
return list_name
# 过滤文件
def get_file_name(list_dir):
result = []
for i in range(len(list_dir)):
if list_dir[i].find(".png") > 0 or list_dir[i].find(".jpg") > 0:
result.append(list_dir[i])
else:
continue
return result
# 得到有效图片列表
def get_figure_list(path):
if path[-1] != '/':
path = path + '/'
figure_list = get_file_name(list_dir(path))
return path, figure_list
# 调用tinypng进行压缩
def compress_figure_exec(figure_list, new_path):
# 遍历压缩
count = 0;
for i in range(len(figure_list)):
figure_name = figure_list[i]
with open(figure_list[i], 'rb') as source:
source_data = source.read()
result = tinify.from_buffer(source_data)
figure_name = os.path.basename(figure_name)
result = result.to_file(new_path + figure_name)
count = count + 1
print(figure_list[i],' -> compress ok !')
print('本月已使用压缩次数:', tinify.compression_count)
return count
# 新建目录用于存放压缩结果
def mkdir_new_path(path):
new_path = os.path.dirname(path) + '_res/'
if not os.path.exists(new_path):
os.makedirs(new_path)
return new_path
# 得到文件列表
path, figure_list = get_figure_list(path)
# 得到新存放路径
if USE_COVER_ORIGIN_FIGURE == 1:
new_path = path
else:
new_path = mkdir_new_path(path)
#压缩处理
res_count = compress_figure_exec(figure_list, new_path)
print("figure_count=", len(figure_list), ", res_count=", res_count)3. 执行脚本
执行脚本过程中,终端打印输出如下:


最终158张图片全部压缩完成,如下:


更多接口函数,参考官网:https://tinypng.com/developers/reference/python
