本文目录导读:

Python脚本(最通用,推荐)
使用Pillow库(简单易用)
from PIL import Image
import os
from pathlib import Path
def compress_images(input_folder, output_folder, quality=85, max_size=(1920, 1080)):
"""
批量压缩图片
:param input_folder: 输入文件夹
:param output_folder: 输出文件夹
:param quality: 压缩质量(1-100)
:param max_size: 最大尺寸,None表示不限制
"""
# 创建输出文件夹
os.makedirs(output_folder, exist_ok=True)
# 支持的文件扩展名
extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.webp'}
# 遍历文件夹
for file_path in Path(input_folder).rglob('*'):
if file_path.suffix.lower() in extensions:
try:
# 打开图片
img = Image.open(file_path)
# 调整尺寸(如需要)
if max_size and img.size > max_size:
img.thumbnail(max_size, Image.Resampling.LANCZOS)
# 处理透明通道
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
# 转换成RGB再保存为JPEG会丢失透明,建议保存为PNG或转白色背景
img = img.convert('RGB')
output_path = os.path.join(output_folder, file_path.stem + '.jpg')
img.save(output_path, 'JPEG', quality=quality, optimize=True)
else:
# 保存压缩后的图片
img = img.convert('RGB')
output_path = os.path.join(output_folder, file_path.stem + '.jpg')
img.save(output_path, 'JPEG', quality=quality, optimize=True)
print(f"✓ 压缩完成: {file_path.name}")
except Exception as e:
print(f"✗ 处理失败 {file_path.name}: {e}")
# 使用示例
if __name__ == "__main__":
compress_images(
input_folder="原始图片文件夹",
output_folder="压缩后文件夹",
quality=80, # 质量调整(越低文件越小)
max_size=(1920, 1080) # 可选:限制最大尺寸
)
使用tinypng API(压缩效果更好,但有API限制)
import tinify
import os
from pathlib import Path
# 注册获取API key: https://tinypng.com/developers
tinify.key = "YOUR_API_KEY"
def compress_with_tinypng(input_folder, output_folder):
os.makedirs(output_folder, exist_ok=True)
extensions = {'.jpg', '.jpeg', '.png', '.webp'}
for file_path in Path(input_folder).rglob('*'):
if file_path.suffix.lower() in extensions:
try:
source = tinify.from_file(str(file_path))
output_path = os.path.join(output_folder, file_path.name)
source.to_file(output_path)
print(f"✓ 压缩完成: {file_path.name}")
except Exception as e:
print(f"✗ 压缩失败 {file_path.name}: {e}")
# 使用
# compress_with_tinypng("原始文件夹", "压缩后文件夹")
命令行批量压缩(Windows/Mac/Linux)
Windows批处理脚本(compress.bat)
@echo off
setlocal enabledelayedexpansion
REM 设置输入输出文件夹
set INPUT_FOLDER=原始图片文件夹
set OUTPUT_FOLDER=压缩后文件夹
REM 创建输出文件夹
if not exist "%OUTPUT_FOLDER%" mkdir "%OUTPUT_FOLDER%"
REM 遍历所有图片文件
for /r "%INPUT_FOLDER%" %%f in (*.jpg *.jpeg *.png *.bmp *.webp) do (
echo 正在压缩: %%~nxf
powershell -Command "Add-Type -AssemblyName System.Drawing; $img = [System.Drawing.Image]::FromFile('%%f'); $maxW = 1920; $maxH = 1080; if ($img.Width -gt $maxW -or $img.Height -gt $gt$maxH) { $ratio = [Math]::Min($maxW / $img.Width, $maxH / $img.Height); $newW = [int]($img.Width * $ratio); $newH = [int]($img.Height * $ratio); $bmp = New-Object System.Drawing.Bitmap $bmp, $newW, $newH; $graphics = [System.Drawing.Graphics]::FromImage($bmp); $graphics.DrawImage($img, 0, 0, $newW, $newH); $bmp.Save('%OUTPUT_FOLDER%\%%~nf.jpg', [System.Drawing.Imaging.ImageFormat]::Jpeg); $graphics.Dispose() } else { $img.Save('%OUTPUT_FOLDER%\%%~nf.jpg', [System.Drawing.Imaging.ImageFormat]::Jpeg) }; $img.Dispose()"
)
echo 压缩完成!
pause
使用ImageMagick(需要安装)
# 批量压缩为JPEG,设置质量
for img in *.jpg *.png *.webp; do
convert "$img" -strip -quality 85 -resize "1920x1080>" "compressed_${img%.*}.jpg"
done
使用Node.js(web开发常用)
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
async function compressImages() {
const inputFolder = './原始图片';
const outputFolder = './压缩后图片';
// 创建输出文件夹
if (!fs.existsSync(outputFolder)) {
fs.mkdirSync(outputFolder, { recursive: true });
}
// 支持的格式
const extensions = ['.jpg', '.jpeg', '.png', '.webp'];
// 读取输入文件夹
const files = fs.readdirSync(inputFolder);
for (const file of files) {
const ext = path.extname(file).toLowerCase();
if (extensions.includes(ext)) {
const inputPath = path.join(inputFolder, file);
const outputPath = path.join(outputFolder, `${path.parse(file).name}.jpg`);
try {
await sharp(inputPath)
.resize(1920, 1080, { withoutEnlargement: true }) // 限制最大尺寸
.jpeg({ quality: 80, progressive: true })
.toFile(outputPath);
console.log(`✓ 压缩完成: ${file}`);
} catch (error) {
console.error(`✗ 处理失败 ${file}:`, error);
}
}
}
console.log('所有图片处理完成!');
}
compressImages();
使用bat+批处理(最简单,但功能有限)
@echo off echo 正在压缩图片... REM 需要安装 ImageMagick magick mogrify -path 压缩后文件夹 -quality 85 -resize "1920x1080>" *.jpg *.png echo 压缩完成! pause
使用方法建议:
- 日常使用推荐:使用Python脚本(最灵活)
- 想要最好压缩率:使用TinyPNG API
- 命令行快速处理:使用ImageMagick或批处理
- 网页项目:使用Node.js脚本
依赖安装:
# Python pip install Pillow pip install tinify # Node.js npm install sharp # 系统工具 # ImageMagick: https://imagemagick.org/script/download.php
需要我帮你调整脚本或解决具体问题吗?