本文目录导读:

- Python 脚本 (最常用)
- 简单命令行版本 (Python)
- Windows 批处理脚本 (使用 ImageMagick)
- Linux/Mac Shell 脚本 (使用 ImageMagick)
- 高级 Python 脚本 (带更多功能)
- 使用说明
我来为您提供批量修改图像分辨率的脚本,这里提供几个不同语言和场景的版本:
Python 脚本 (最常用)
import os
from PIL import Image
import glob
def batch_resize_images(input_dir, output_dir, new_size, suffix="_resized"):
"""
批量修改图像分辨率
Args:
input_dir: 输入文件夹路径
output_dir: 输出文件夹路径
new_size: 新尺寸元组 (width, height)
suffix: 输出文件名后缀
"""
# 创建输出目录
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 支持的图片格式
image_extensions = ['*.jpg', '*.jpeg', '*.png', '*.bmp', '*.gif', '*.tiff']
# 遍历所有图片文件
for ext in image_extensions:
for filepath in glob.glob(os.path.join(input_dir, ext)):
try:
# 打开图片
with Image.open(filepath) as img:
# 修改尺寸
resized_img = img.resize(new_size, Image.Resampling.LANCZOS)
# 生成输出文件名
filename = os.path.basename(filepath)
name, ext = os.path.splitext(filename)
output_filename = f"{name}{suffix}{ext}"
output_path = os.path.join(output_dir, output_filename)
# 保存图片
resized_img.save(output_path)
print(f"处理完成: {filename} -> {output_filename}")
except Exception as e:
print(f"处理 {filepath} 时出错: {e}")
# 使用示例
if __name__ == "__main__":
# 请修改以下参数
input_folder = "./input_images" # 输入文件夹
output_folder = "./output_images" # 输出文件夹
new_width = 1920 # 目标宽度
new_height = 1080 # 目标高度
batch_resize_images(input_folder, output_folder, (new_width, new_height))
简单命令行版本 (Python)
import sys
from PIL import Image
import glob
import os
def main():
if len(sys.argv) < 4:
print("用法: python resize_images.py <输入目录> <输出目录> <宽度> [高度]")
print("示例: python resize_images.py ./input ./output 800 600")
sys.exit(1)
input_dir = sys.argv[1]
output_dir = sys.argv[2]
width = int(sys.argv[3])
height = int(sys.argv[4]) if len(sys.argv) > 4 else width # 默认正方形
batch_resize_images(input_dir, output_dir, (width, height))
def batch_resize_images(input_dir, output_dir, new_size):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for ext in ['*.jpg', '*.jpeg', '*.png']:
for filepath in glob.glob(os.path.join(input_dir, ext)):
try:
with Image.open(filepath) as img:
resized = img.resize(new_size, Image.Resampling.LANCZOS)
output_path = os.path.join(output_dir, os.path.basename(filepath))
resized.save(output_path)
print(f"✓ {os.path.basename(filepath)}")
except Exception as e:
print(f"✗ {os.path.basename(filepath)}: {e}")
if __name__ == "__main__":
main()
Windows 批处理脚本 (使用 ImageMagick)
@echo off
echo 批量修改图像分辨率脚本
echo 需要安装 ImageMagick: https://imagemagick.org
echo.
REM 设置参数
set INPUT_DIR=.\input
set OUTPUT_DIR=.\output
set WIDTH=1920
set HEIGHT=1080
REM 创建输出目录
if not exist "%OUTPUT_DIR%" mkdir "%OUTPUT_DIR%"
REM 处理所有图片文件
for %%f in ("%INPUT_DIR%\*.jpg" "%INPUT_DIR%\*.png" "%INPUT_DIR%\*.jpeg") do (
echo 处理: %%~nxf
magick convert "%%f" -resize %WIDTH%x%HEIGHT%! "%OUTPUT_DIR%\%%~nxf"
)
echo.
echo 处理完成!
pause
Linux/Mac Shell 脚本 (使用 ImageMagick)
#!/bin/bash
# 批量修改图像分辨率
# 需要安装 ImageMagick: sudo apt-get install imagemagick (Ubuntu)
# 或 brew install imagemagick (Mac)
INPUT_DIR="./input"
OUTPUT_DIR="./output"
WIDTH=1920
HEIGHT=1080
# 创建输出目录
mkdir -p "$OUTPUT_DIR"
# 支持的图片格式
EXTENSIONS=("jpg" "jpeg" "png" "bmp" "gif")
for ext in "${EXTENSIONS[@]}"; do
for file in "$INPUT_DIR"/*."$ext"; do
if [ -f "$file" ]; then
filename=$(basename "$file")
echo "处理: $filename"
convert "$file" -resize "${WIDTH}x${HEIGHT}!" "$OUTPUT_DIR/$filename"
fi
done
done
echo "处理完成!"
高级 Python 脚本 (带更多功能)
import os
import argparse
from PIL import Image
from pathlib import Path
import concurrent.futures
def resize_image(filepath, output_dir, new_size, quality=95):
"""处理单张图片"""
try:
with Image.open(filepath) as img:
# 保持宽高比
if new_size[0] is None or new_size[1] is None:
img.thumbnail(new_size, Image.Resampling.LANCZOS)
else:
img = img.resize(new_size, Image.Resampling.LANCZOS)
# 生成输出路径
output_path = os.path.join(output_dir, os.path.basename(filepath))
# 根据格式保存
ext = Path(filepath).suffix.lower()
if ext in ['.jpg', '.jpeg']:
img.save(output_path, 'JPEG', quality=quality)
elif ext == '.png':
img.save(output_path, 'PNG')
else:
img.save(output_path)
return True, filepath
except Exception as e:
return False, f"{filepath}: {e}"
def batch_resize_advanced(input_dir, output_dir, width, height,
keep_aspect=True, quality=95, workers=4):
"""批量处理图片"""
# 创建输出目录
Path(output_dir).mkdir(parents=True, exist_ok=True)
# 收集所有图片文件
image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp'}
files = []
for ext in image_extensions:
files.extend(Path(input_dir).glob(f'*{ext}'))
files.extend(Path(input_dir).glob(f'*{ext.upper()}'))
print(f"找到 {len(files)} 个图片文件")
# 计算目标尺寸
if keep_aspect:
new_size = (width, height) # thumbnail 模式
else:
new_size = (width, height) # 强制 resize
# 多线程处理
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
futures = [
executor.submit(resize_image, str(f), output_dir, new_size, quality)
for f in files
]
for future in concurrent.futures.as_completed(futures):
success, msg = future.result()
status = "✓" if success else "✗"
print(f"{status} {msg}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='批量修改图像分辨率')
parser.add_argument('input', help='输入目录')
parser.add_argument('output', help='输出目录')
parser.add_argument('width', type=int, help='目标宽度')
parser.add_argument('height', type=int, help='目标高度')
parser.add_argument('--no-aspect', action='store_true',
help='不保持宽高比(默认保持)')
parser.add_argument('--quality', type=int, default=95,
help='JPEG质量 (1-100)')
parser.add_argument('--workers', type=int, default=4,
help='并行处理线程数')
args = parser.parse_args()
batch_resize_advanced(
args.input,
args.output,
args.width,
args.height,
keep_aspect=not args.no_aspect,
quality=args.quality,
workers=args.workers
)
使用说明
安装依赖
Python 版本需要安装 PIL:
pip install Pillow
Shell 版本需要安装 ImageMagick:
- Ubuntu/Debian:
sudo apt-get install imagemagick - Mac:
brew install imagemagick - Windows: 下载安装包
使用方法
-
简单 Python 脚本:
python resize_images.py ./input ./output 800 600
-
高级 Python 脚本:
python batch_resize_advanced.py ./input ./output 1920 1080 --quality 90
-
保持目录结构:
# 修改脚本添加子目录支持 import shutil # 在脚本中遍历子目录
这些脚本可以根据您的具体需求进行修改和调整,需要我帮您定制特定的功能吗?