Compress and optimize image files with full control over quality, target file size, output format, and dimensions. Supports single images and batch directory processing.
JPEG, PNG, WebP, GIF, BMP, TIFF
The core script is located at: scripts/compress_image.py
Requires Pillow. If not installed, run: pip install Pillow
python scripts/compress_image.py <input> [options]
| Option | Description | Default |
|---|---|---|
| -------- | ------------- | --------- |
-o, --output | Output file or directory | next to input |
-q, --quality <1-95> | JPEG/WebP quality | 85 |
-s, --max-size | Target max file size in KB (auto-adjusts quality) | None |
-f, --format | Output format: jpeg, png, webp, gif | Keep original |
-w, --width | Resize width (preserves aspect ratio) | No resize |
-H, --height | Resize height (preserves aspect ratio) | No resize |
--batch | Batch process all images in a directory | Off |
--no-overwrite | Skip files that already exist at output path | Off |
-v, --verbose | Show per-file size and quality info | Off |
python scripts/compress_image.py photo.jpg -q 80 -v
python scripts/compress_image.py photo.jpg -s 200 -v
# → Automatically finds the highest quality that fits within 200 KB
python scripts/compress_image.py image.png -f webp -q 85 -o output/
python scripts/compress_image.py photo.jpg -w 1920 -q 85 -o resized/
python scripts/compress_image.py ./images/ --batch -q 80 -v
# → Outputs to ./images/compressed/
python scripts/compress_image.py ./images/ --batch -f webp -s 300 -o ./webp_output/ -v
-q 85 -v.-s which auto-finds the best quality.-q controls compress level, not visual quality.-v to show the user before/after file sizes and compression ratio.pip install Pillow before executing the script.共 1 个版本