本文主要介绍如何方便的使用 tinypng 工具进行批量图片压缩
注册一个账号,获取 API Key https://tinypng.com/
安装 python 并安装 tinify 库
bash
pip install --upgrade tinify
- 创建一个 compress.py 文件,复制以下代码,并将 "API Key" 替换为你的 API Key
python
import tinify
import os
import sys
# 替换成你的 API Key
tinify.key = "API Key"
input_dir = "./images"
output_dir = "./compressed"
# 创建输出目录(如果不存在)
os.makedirs(output_dir, exist_ok=True)
# 如果输入目录不存在,就新建并退出
if not os.path.isdir(input_dir):
os.makedirs(input_dir, exist_ok=True)
print("❌ images 输入目录不存在,现已为你创建,请将图片放入其中后再运行。")
sys.exit(0)
# 找出所有候选文件
candidates = [
f for f in os.listdir(input_dir)
if f.lower().endswith((".png", ".jpg", ".jpeg", ".webp", ".avif"))
]
# 如果没有候选文件,给出提示并退出
if not candidates:
print("⚠️ 没有找到可压缩的图片,请将 PNG/JPG/WEBP/AVIF 文件放入 images 目录。")
sys.exit(0)
# 遍历候选文件
for file in candidates:
input_path = os.path.join(input_dir, file)
output_path = os.path.join(output_dir, file)
# 如果输出文件已存在,就跳过
if os.path.exists(output_path):
print(f" ➡️ 跳过: {file} (已存在于输出目录)")
continue
# 获取原始大小
before_size = os.path.getsize(input_path) / 1024
# 调用 TinyPNG API 压缩
source = tinify.from_file(input_path)
source.to_file(output_path)
# 获取压缩后大小
after_size = os.path.getsize(output_path) / 1024
ratio = (1 - after_size / before_size) * 100
print(f"✅ 压缩完成: {file} | {before_size:.2f} KB → {after_size:.2f} KB | 压缩率: {ratio:.2f}%")
- 创建一个批处理脚本 run.bat,复制以下代码
bat
@echo off
py compress.py
pause
- 将你想压缩的图片放入 images 目录,双击运行 run.bat 即可,压缩后的图片会保存在 compressed 目录中