使用 Python Tinify 高效批量压缩图片,优化 Webpack 打包速度!
发布时间:2025-06-24 17:13:22 作者:北方职教升学中心 阅读量:636
webpack。本身可以压缩图片。image-webpack-loader。,但是打包时间长图片是。有损压缩。用于图片质量。Python tinify。库脚本压缩。
以下是基于 。Python。 的 。Tinify。(TinyPNG)图片压缩脚本,它可以 。递归压缩。 指定目录下的一切 。JPG、PNG 和 WebP。 图片,并 。统计压缩前后的总尺寸和节省的空间。。
I.代码功能。
- 遍历目录及其子目录。,查找 。
jpg。
、。png。
、。webp。
图片文件。 - 使用 Tinify API 无损压缩,保证图片质量
- 输出压缩前后尺寸对比。,显示节省空间。
- 跳过压缩图片。,避免重复操作。
2.Python
python复制和编辑import osimport sysimport 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("⚠️ 未找到需要压缩的图片")# 获得命令行参数(#xff09目标目录;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)。
三、如何使用。
三、如何使用。
安装依赖。
复制pip编辑 install tinify。
- 获取 Tinify API Key。
- 到 inyPNG API(TinyPNG – Optimize AVIF, WebP, JPEG and PNG Images with TinyPNG API)申请开发者 API Key。
将 。
TINIFY_API_KEY = "your_tinify_api_key"
替换成你的 API Key。
运行脚本。
python复制编辑器 compress_images.py "/your/image/directory"
例如:
python复制编辑器 compress_images.py "./images"
四、代码优化点。✅ 。
处理子目录自动递归。✅ 。
检查图片格式,避免处理非图片文件。✅ 。
异常处理(API 错误,服务器异常,无效路径)✅ 。
输出详细的压缩信息,统计节省空间。✅ 。
避免重复压缩。
五、运行效果示例。
x1f680复制编辑; 开始压缩目录: ./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 打包时间同时。保持高画质。
!