本文目录导读:

我来为您介绍几种批量调整图片尺寸的方法,包括使用脚本和软件:
Python脚本(最推荐)
使用PIL/Pillow库
import os
from PIL import Image
import glob
def batch_resize(input_folder, output_folder, target_size=(800, 600)):
"""批量调整图片尺寸"""
# 创建输出文件夹
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 支持的图片格式
extensions = ['*.jpg', '*.jpeg', '*.png', '*.bmp', '*.gif']
for ext in extensions:
for filepath in glob.glob(os.path.join(input_folder, ext)):
try:
# 打开图片
with Image.open(filepath) as img:
# 保持比例调整大小
img.thumbnail(target_size, Image.LANCZOS)
# 保存到输出文件夹
filename = os.path.basename(filepath)
output_path = os.path.join(output_folder, filename)
img.save(output_path)
print(f"已处理: {filename}")
except Exception as e:
print(f"处理 {filepath} 时出错: {e}")
# 使用示例
batch_resize("输入文件夹路径", "输出文件夹路径", (800, 600))
更高级的版本(带参数控制)
import os
from PIL import Image
import argparse
def resize_images(source_dir, target_dir, width=None, height=None, quality=85):
"""批量调整图片尺寸,支持更多选项"""
if not os.path.exists(target_dir):
os.makedirs(target_dir)
for filename in os.listdir(source_dir):
if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp', '.gif')):
try:
img_path = os.path.join(source_dir, filename)
with Image.open(img_path) as img:
original_width, original_height = img.size
# 计算新的尺寸
if width and height:
# 指定宽高
new_size = (width, height)
elif width:
# 只指定宽度,高度按比例
ratio = width / original_width
new_size = (width, int(original_height * ratio))
elif height:
# 只指定高度,宽度按比例
ratio = height / original_height
new_size = (int(original_width * ratio), height)
else:
continue
# 调整大小
resized_img = img.resize(new_size, Image.LANCZOS)
# 保存图片
output_path = os.path.join(target_dir, filename)
resized_img.save(output_path, quality=quality, optimize=True)
print(f"已处理: {filename} ({original_width}x{original_height} -> {new_size[0]}x{new_size[1]})")
except Exception as e:
print(f"处理 {filename} 失败: {e}")
# 命令行参数支持
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='批量调整图片尺寸')
parser.add_argument('source', help='源文件夹路径')
parser.add_argument('target', help='目标文件夹路径')
parser.add_argument('-w', '--width', type=int, help='目标宽度')
parser.add_argument('-h', '--height', type=int, help='目标高度')
parser.add_argument('-q', '--quality', type=int, default=85, help='图片质量 (1-100)')
args = parser.parse_args()
resize_images(args.source, args.target, args.width, args.height, args.quality)
Bash/PowerShell脚本
Linux/Mac 使用ImageMagick
#!/bin/bash
# resize_images.sh
# 批量调整所有jpg图片为800x600
for img in *.jpg; do
convert "$img" -resize 800x600 "resized_$img"
echo "已处理: $img"
done
# 保持比例调整
for img in *.jpg; do
convert "$img" -resize 800 "resized_$img"
echo "已处理: $img"
done
Windows PowerShell
# 使用.NET的System.Drawing
Add-Type -AssemblyName System.Drawing
$sourceFolder = "C:\图片文件夹"
$targetFolder = "C:\输出文件夹"
$maxWidth = 800
$maxHeight = 600
# 创建输出文件夹
if (!(Test-Path $targetFolder)) {
New-Item -ItemType Directory -Path $targetFolder
}
# 处理所有图片
Get-ChildItem -Path $sourceFolder -Include *.jpg,*.jpeg,*.png,*.bmp -Recurse | ForEach-Object {
try {
$img = [System.Drawing.Image]::FromFile($_.FullName)
$ratio = [Math]::Min($maxWidth / $img.Width, $maxHeight / $img.Height)
if ($ratio -lt 1) {
$newWidth = [int]($img.Width * $ratio)
$newHeight = [int]($img.Height * $ratio)
$bitmap = New-Object System.Drawing.Bitmap($newWidth, $newHeight)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.DrawImage($img, 0, 0, $newWidth, $newHeight)
$outputPath = Join-Path $targetFolder $_.Name
$bitmap.Save($outputPath, [System.Drawing.Imaging.ImageFormat]::Jpeg)
Write-Host "已处理: $($_.Name) (${newWidth}x${newHeight})"
$graphics.Dispose()
$bitmap.Dispose()
}
$img.Dispose()
}
catch {
Write-Host "处理 $($_.Name) 时出错: $_"
}
}
使用现成工具
ImageMagick命令行
# 批量调整所有图片到最大800x600 mogrify -path ./output -resize 800x600 *.jpg # 批量调整到指定像素 mogrify -path ./output -resize 800x600! *.jpg # 强制尺寸 # 批量调整并保持比例 mogrify -path ./output -resize 800x600\> *.jpg # 仅缩小 mogrify -path ./output -resize 800x600\< *.jpg # 仅放大
使用sips (Mac系统自带)
# 批量调整图片
for file in *.jpg; do
sips -Z 800 "$file" --out "resized_$file"
done
# -Z 参数表示最大尺寸,保持比例
GUI批量处理工具推荐
- XnConvert (免费、跨平台)
- FastStone Photo Resizer (Windows)
- IrfanView (Windows,带批量处理功能)
- GIMP (免费,支持批处理)
安装必要依赖
# Python pip install Pillow # ImageMagick # Ubuntu/Debian sudo apt-get install imagemagick # Mac brew install imagemagick # Windows # 下载安装包: https://imagemagick.org/script/download.php
使用建议
- 备份原始文件:批量操作前务必备份
- 选择合适的插值算法:
LANCZOS:高质量,适合缩小BILINEAR:较快,中等质量NEAREST:最快,质量最差
- 设置合理的质量参数:一般85-95%即可兼顾质量和大小
- 处理大文件时:注意内存占用,分批处理
根据您的具体需求选择最适合的方法,如果需要更多定制功能,推荐使用Python脚本。