webpackCan compress pictures by itselfimage-webpack-loader, but the packaging time is long, the picture isLossy compressionFor the quality of the picturePython tinifyLibrary script compression
The following is a basedPythonofTinify(TinyPNG) library image compression script, it canRecursive compressionAll in the specified directoryJPG, PNG and WebPPictures, andStatistics the total size before and after compression and space saved。
1. Code function
-
Traverse directory and its subdirectories, find
jpg
、png
、webp
Picture files - Lossless compression using the Tinify API, ensure the quality of the picture
- Comparison of size before and after output compression, display saves space
- Skip compressed images, avoid repeated operations
2. Python code
import os import sys import tinify # Set up the Tinify API Key (please go to /developers to get it yourself)TINIFY_API_KEY = "your_tinify_api_key" = TINIFY_API_KEY # Supported image formatsSUPPORTED_FORMATS = (".jpg", ".jpeg", ".png", ".webp") # Recursively compressed imagesdef compress_images_in_directory(directory): total_original_size = 0 total_compressed_size = 0 compressed_count = 0 # traverse directory and subdirectories for root, _, files in (directory): for file in files: if ().endswith(SUPPORTED_FORMATS): # Only images in the specified format are processed file_path = (root, file) original_size = (file_path) # Get the original file size try: # Compress pictures source = tinify.from_file(file_path) source.to_file(file_path) compressed_size = (file_path) # Get the compressed size compressed_count += 1 total_original_size += original_size total_compressed_size += compressed_size # Output compressed log saved_size = original_size - compressed_size print(f"✅ Compression successfully: {file_path} | save {saved_size / 1024:.2f} KB") except : print("❌ Account verification failed, please check whether the API Key is correct") (1) except : print(f"❌ Unable to process pictures: {file_path}") except : print("❌ TinyPNG server error, try again later") except Exception as e: print(f"❌ An error occurred: {e}") # Summarize the compression results if compressed_count > 0: saved_space = total_original_size - total_compressed_size print("\n📊 Compression Statistics:") print(f"- Number of images processed: {compressed_count}") print(f"- Total size before compression: {total_original_size / 1024:.2f} KB") print(f"- Total size after compression: {total_compressed_size / 1024:.2f} KB") print(f"- 总共save空间: {saved_space / 1024:.2f} KB") else: print("⚠️ No picture to be compressed was found") # Get command line parameters (target directory)if __name__ == "__main__": if len() < 2: print("❌ Please enter the directory path to compress") (1) target_directory = [1] if not (target_directory): print("❌ The specified path is not a valid directory") (1) print(f"🚀 Start compressing the directory: {target_directory}\n") compress_images_in_directory(target_directory)
3. How to use
Installation dependencies
pip install tinify
Get the Tinify API Key
- To the TinyPNG API(/developers) Apply for Developer API Key
- Will
TINIFY_API_KEY = "your_tinify_api_key"
Replace with your API Key
Run the script
python compress_images.py "/your/image/directory"
For example:
python compress_images.py "./images"
4. Code optimization points
Automatic recursive processing of subdirectories
Check image format to avoid processing non-image files
Exception handling (API error, server exception, invalid path)
Output detailed compression information, save space by statistics
Avoid repeated compression
5. Running effect examples
🚀 Start compressing the directory: ./images
✅ Compression successfully: ./images/ | Save 45.3 KB
✅ Compression successfully: ./images/ | Save 30.7 KB
✅ Compression successfully: ./images/subdir/ | Save 25.1 KB
📊 Compression statistics:
- Number of images processed: 3
- Total size before compression: 512.3 KB
- Total size after compression: 411.2 KB
- Total space savings: 101.1 KB
That way, you canBefore Webpack build,Manually use Python scripts to batch compress images, reduce Webpack packaging time, and at the same timeMaintain high picture quality!
This is the article about Python + Tinify's efficient batch compression of pictures. For more related Python compressed pictures, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!