使用 Python + Tinify 高效批量压缩图片,优化 Webpack 打包速度!

发布于:2025-02-25 ⋅ 阅读:(12) ⋅ 点赞:(0)

webpack本身可以压缩图片image-webpack-loader,但是打包时间长,图片是有损压缩为了图片质量采用Python tinify库脚本压缩

以下是一个基于 Python 的 Tinify(TinyPNG)库的图片压缩脚本,它可以 递归压缩 指定目录下的所有 JPG、PNG 和 WebP 图片,并 统计压缩前后的总大小及节省的空间


一、代码功能

  • 遍历目录及其子目录,查找 jpgpngwebp 图片文件
  • 使用 Tinify API 进行无损压缩,保证图片质量
  • 输出压缩前后大小对比,显示节省空间
  • 跳过已压缩的图片,避免重复操作

二、Python 代码

python
复制编辑
import os
import sys
import tinify

# 设置 Tinify API Key(请自行到 https://tinypng.com/developers 获取)
TINIFY_API_KEY = "your_tinify_api_key"
tinify.key = TINIFY_API_KEY

# 支持的图片格式
SUPPORTED_FORMATS = (".jpg", ".jpeg", ".png", ".webp")

# 递归压缩图片
def compress_images_in_directory(directory):
    total_original_size = 0
    total_compressed_size = 0
    compressed_count = 0

    # 遍历目录及子目录
    for root, _, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(SUPPORTED_FORMATS):  # 仅处理指定格式的图片
                file_path = os.path.join(root, file)
                original_size = os.path.getsize(file_path)  # 获取原始文件大小

                try:
                    # 压缩图片
                    source = tinify.from_file(file_path)
                    source.to_file(file_path)
                    
                    compressed_size = os.path.getsize(file_path)  # 获取压缩后大小
                    compressed_count += 1
                    total_original_size += original_size
                    total_compressed_size += compressed_size

                    # 输出压缩日志
                    saved_size = original_size - compressed_size
                    print(f"✅ 压缩成功: {file_path} | 节省 {saved_size / 1024:.2f} KB")
                except tinify.errors.AccountError:
                    print("❌ 账户验证失败,请检查 API Key 是否正确")
                    sys.exit(1)
                except tinify.errors.ClientError:
                    print(f"❌ 无法处理图片: {file_path}")
                except tinify.errors.ServerError:
                    print("❌ TinyPNG 服务器错误,稍后再试")
                except Exception as e:
                    print(f"❌ 发生错误: {e}")

    # 总结压缩结果
    if compressed_count > 0:
        saved_space = total_original_size - total_compressed_size
        print("\n📊 压缩统计:")
        print(f"- 处理图片数量: {compressed_count}")
        print(f"- 压缩前总大小: {total_original_size / 1024:.2f} KB")
        print(f"- 压缩后总大小: {total_compressed_size / 1024:.2f} KB")
        print(f"- 总共节省空间: {saved_space / 1024:.2f} KB")
    else:
        print("⚠️ 未找到需要压缩的图片")

# 获取命令行参数(目标目录)
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("❌ 请输入要压缩的目录路径")
        sys.exit(1)

    target_directory = sys.argv[1]
    
    if not os.path.isdir(target_directory):
        print("❌ 指定的路径不是一个有效目录")
        sys.exit(1)

    print(f"🚀 开始压缩目录: {target_directory}\n")
    compress_images_in_directory(target_directory)

三、如何使用

  1. 安装依赖

    复制编辑
    pip install tinify

  2. 获取 Tinify API Key

  3. 运行脚本

    复制编辑
    python compress_images.py "/your/image/directory"

    例如:

    复制编辑
    python compress_images.py "./images"


四、代码优化点

✅ 自动递归处理子目录
✅ 检查图片格式,避免处理非图片文件
✅ 异常处理(API 错误、服务器异常、无效路径)
✅ 输出详细的压缩信息,统计节省空间
✅ 避免重复压缩


五、运行效果示例

复制编辑
🚀 开始压缩目录: ./images

✅ 压缩成功: ./images/photo1.jpg | 节省 45.3 KB
✅ 压缩成功: ./images/photo2.png | 节省 30.7 KB
✅ 压缩成功: ./images/subdir/photo3.webp | 节省 25.1 KB

📊 压缩统计:
- 处理图片数量: 3
- 压缩前总大小: 512.3 KB
- 压缩后总大小: 411.2 KB
- 总共节省空间: 101.1 KB

这样,你就可以 在 Webpack 构建前手动使用 Python 脚本批量压缩图片,减少 Webpack 打包时间,同时保持高画质