本文目录导读:

- Python 脚本(最推荐,跨平台,功能强)
- Shell 脚本(Linux/macOS 使用,需要安装
jpegoptim和optipng) - Windows 批处理脚本(使用 ImageMagick)
- 使用建议
这里提供几个不同场景下的批量压缩图片脚本,涵盖 Python、Shell 和 Windows 批处理,你可以根据操作系统和使用习惯选择。
Python 脚本(最推荐,跨平台,功能强)
依赖安装:
pip install Pillow
基础版本:按百分比压缩
import os
from PIL import Image
import sys
def compress_images(input_dir, output_dir, quality=85, max_size=(1920, 1080)):
"""
批量压缩图片
:param input_dir: 输入文件夹路径
:param output_dir: 输出文件夹路径
:param quality: 压缩质量 (1-100),数字越小压缩越狠
:param max_size: 最大尺寸 (宽, 高),None 表示不限制
"""
# 创建输出文件夹
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 支持的图片格式
supported_formats = ('.jpg', '.jpeg', '.png', '.bmp', '.webp')
# 遍历输入文件夹
for filename in os.listdir(input_dir):
if filename.lower().endswith(supported_formats):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
try:
# 打开图片
with Image.open(input_path) as img:
# 输出原始信息
orig_size = os.path.getsize(input_path)
print(f"处理: {filename}")
print(f" 原始: {img.size[0]}x{img.size[1]}, {orig_size/1024:.1f}KB")
# 调整尺寸(如果需要)
if max_size:
img.thumbnail(max_size, Image.Resampling.LANCZOS)
# 保存压缩后的图片
img.save(output_path, quality=quality, optimize=True)
# 输出压缩后信息
new_size = os.path.getsize(output_path)
ratio = (1 - new_size/orig_size) * 100
print(f" 压缩后: {img.size[0]}x{img.size[1]}, {new_size/1024:.1f}KB (减小了{ratio:.1f}%)")
except Exception as e:
print(f" 错误: {filename} - {str(e)}")
if __name__ == "__main__":
# 使用示例
input_dir = "input_images" # 存放原始图片的文件夹
output_dir = "compressed_images" # 存放压缩后图片的文件夹
# 参数可调整
compress_images(
input_dir=input_dir,
output_dir=output_dir,
quality=75, # 质量,75通常是不错的选择
max_size=(1920, 1080) # 最大分辨率
)
print("批量压缩完成!")
进阶版本:支持更多格式和递归处理
import os
from PIL import Image
import concurrent.futures
def compress_image(file_info):
"""单个图片压缩任务"""
input_path, output_dir, quality, max_size = file_info
filename = os.path.basename(input_path)
output_path = os.path.join(output_dir, filename)
try:
with Image.open(input_path) as img:
orig_size = os.path.getsize(input_path)
# 转为RGB以支持所有格式保存为JPEG
if img.mode in ('RGBA', 'LA', 'P'):
# PNG透明图片保留PNG格式
if img.mode == 'RGBA':
# 保留透明通道,保存为PNG
if max_size:
img.thumbnail(max_size, Image.Resampling.LANCZOS)
img.save(output_path, 'PNG', optimize=True)
else:
img = img.convert('RGB')
if max_size:
img.thumbnail(max_size, Image.Resampling.LANCZOS)
img.save(output_path, quality=quality, optimize=True)
else:
img = img.convert('RGB')
if max_size:
img.thumbnail(max_size, Image.Resampling.LANCZOS)
img.save(output_path, quality=quality, optimize=True)
new_size = os.path.getsize(output_path)
ratio = (1 - new_size/orig_size) * 100
return f"✓ {filename}: {orig_size/1024:.1f}→{new_size/1024:.1f}KB ({ratio:.1f}%)"
except Exception as e:
return f"✗ {filename}: 错误 - {str(e)}"
def batch_compress(input_dir, output_dir, quality=75, max_size=(1920, 1080), recursive=True):
"""批量压缩图片(支持多线程)"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
supported_formats = ('.jpg', '.jpeg', '.png', '.bmp', '.webp', '.tiff')
file_list = []
if recursive:
for root, dirs, files in os.walk(input_dir):
for file in files:
if file.lower().endswith(supported_formats):
input_path = os.path.join(root, file)
file_list.append((input_path, output_dir, quality, max_size))
else:
for file in os.listdir(input_dir):
if file.lower().endswith(supported_formats):
input_path = os.path.join(input_dir, file)
file_list.append((input_path, output_dir, quality, max_size))
print(f"发现 {len(file_list)} 张图片,开始压缩...")
# 多线程压缩
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
results = executor.map(compress_image, file_list)
for result in results:
print(result)
print("压缩完成!")
if __name__ == "__main__":
batch_compress(
input_dir="photos",
output_dir="compressed_photos",
quality=70,
max_size=(1920, 1080),
recursive=True
)
Shell 脚本(Linux/macOS 使用,需要安装 jpegoptim 和 optipng)
#!/bin/bash
# 批量压缩图片脚本
# 需要安装:sudo apt install jpegoptim optipng (Ubuntu)
# 或 brew install jpegoptim optipng (macOS)
INPUT_DIR="${1:-./images}"
OUTPUT_DIR="${2:-./compressed}"
QUALITY="${3:-85}"
# 检查工具
check_dependencies() {
if ! command -v jpegoptim &> /dev/null; then
echo "需要安装 jpegoptim: brew install jpegoptim 或 apt install jpegoptim"
exit 1
fi
if ! command -v optipng &> /dev/null; then
echo "需要安装 optipng: brew install optipng 或 apt install optipng"
exit 1
fi
}
# 创建输出目录
mkdir -p "$OUTPUT_DIR"
check_dependencies
echo "输入目录: $INPUT_DIR"
echo "输出目录: $OUTPUT_DIR"
echo "质量设置: $QUALITY"
echo "开始压缩..."
# 压缩JPEG
for file in "$INPUT_DIR"/*.{jpg,jpeg,JPG,JPEG}; do
if [ -f "$file" ]; then
filename=$(basename "$file")
echo "处理: $filename"
cp "$file" "$OUTPUT_DIR/$filename"
jpegoptim --max="$QUALITY" --strip-all --dest="$OUTPUT_DIR" "$file" > /dev/null 2>&1
if [ $? -eq 0 ]; then
orig=$(stat -f%z "$file" 2>/dev/null || stat -c%s "$file" 2>/dev/null)
new=$(stat -f%z "$OUTPUT_DIR/$filename" 2>/dev/null || stat -c%s "$OUTPUT_DIR/$filename" 2>/dev/null)
ratio=$(echo "scale=1; (1 - $new/$orig) * 100" | bc)
echo " 压缩率: ${ratio}%"
fi
fi
done
# 压缩PNG
for file in "$INPUT_DIR"/*.png; do
if [ -f "$file" ]; then
filename=$(basename "$file")
echo "处理: $filename"
cp "$file" "$OUTPUT_DIR/$filename"
optipng -o7 -out "$OUTPUT_DIR/$filename" "$file" > /dev/null 2>&1
orig=$(stat -f%z "$file" 2>/dev/null || stat -c%s "$file" 2>/dev/null)
new=$(stat -f%z "$OUTPUT_DIR/$filename" 2>/dev/null || stat -c%s "$OUTPUT_DIR/$filename" 2>/dev/null)
ratio=$(echo "scale=1; (1 - $new/$orig) * 100" | bc)
echo " 压缩率: ${ratio}%"
fi
done
echo "批量压缩完成!"
使用方式:
# 给脚本添加执行权限 chmod +x compress_images.sh # 运行(默认压缩 ./images 文件夹) ./compress_images.sh # 指定参数 ./compress_images.sh ./photos ./compressed 70
Windows 批处理脚本(使用 ImageMagick)
首先下载安装 ImageMagick(选择 Windows 版本)。
@echo off
setlocal enabledelayedexpansion
:: 批量压缩图片脚本 for Windows
:: 需要安装 ImageMagick
:: 配置参数
set "INPUT_DIR=input_images"
set "OUTPUT_DIR=compressed_images"
set "QUALITY=75"
set "MAX_WIDTH=1920"
set "MAX_HEIGHT=1080"
echo ========================================
echo 批量图片压缩工具
echo 输入目录: %INPUT_DIR%
echo 输出目录: %OUTPUT_DIR%
echo 质量设置: %QUALITY%%
echo 最大尺寸: %MAX_WIDTH%x%MAX_HEIGHT%
echo ========================================
:: 检查 ImageMagick 是否安装
where magick >nul 2>nul
if %errorlevel% neq 0 (
echo 错误: 未找到 ImageMagick,请先安装
echo 下载地址: https://imagemagick.org/script/download.php
pause
exit /b 1
)
:: 创建输出目录
if not exist "%OUTPUT_DIR%" mkdir "%OUTPUT_DIR%"
:: 遍历输入目录中的图片
for %%f in ("%INPUT_DIR%\*.jpg" "%INPUT_DIR%\*.jpeg" "%INPUT_DIR%\*.png" "%INPUT_DIR%\*.bmp") do (
if exist "%%f" (
set "filename=%%~nxf"
set "filesize=%%~zf"
echo 处理: %%~nxf
:: 获取原始文件大小
set /a orig_size=%%~zf / 1024
:: 压缩并调整尺寸
magick "%%f" -resize %MAX_WIDTH%x%MAX_HEIGHT%^> -quality %QUALITY% "%OUTPUT_DIR%\%%~nxf"
:: 计算压缩率
for %%g in ("%OUTPUT_DIR%\%%~nxf") do (
set /a new_size=%%~zg / 1024
if !orig_size! gtr 0 (
set /a ratio=100 - (!new_size! * 100 / !orig_size!)
echo 原始: !orig_size!KB ^| 压缩后: !new_size!KB ^| 减小了: !ratio!%%
)
)
)
)
echo.
echo 批量压缩完成!
pause
使用方式:
- 将上面的代码保存为
compress_images.bat - 在脚本所在目录创建
input_images文件夹,放入要压缩的图片 - 双击运行脚本
使用建议
| 场景 | 推荐方法 | 质量设置 |
|---|---|---|
| 网页使用 | Python 脚本 | 60-75 |
| 邮件附件 | Python 脚本 | 50-60 |
| 存档备份 | Shell 脚本 | 80-85 |
| 微信/社交分享 | Python + 限制尺寸 | 70 + 1920px |
| 批量处理大量文件 | Shell/批处理 | 按需调整 |
关键提示:
- 建议保留原始文件备份,压缩是不可逆操作
- 对于 PNG 图片(尤其是带透明通道的),压缩效果有限,建议直接调整尺寸
- 使用前先在一个小文件夹测试,确认效果满意后再批量处理
- 如果需要 WebP 格式(更高效的压缩),Python 脚本可以轻松扩展支持