基于Python编写一个批量图片处理工具
更新时间:2026年06月25日 09:01:01 作者:不爱说话的分院帽
这篇文章主要介绍了基于Python编写一个批量图片处理工具,支持批量修改图片尺寸,重命名及格式转换等功能,文中的示例代码讲解详细,有需要的小伙伴可以了解下
功能清单
- 批量修改图片尺寸(统一宽高)
- 批量重命名(自定义前缀 + 序号)
- 图片格式批量转换:jpg ↔ png ↔ webp
- 批量添加文字水印
- 自动遍历文件夹,跳过非图片文件
- 处理后的图片自动输出到 output 文件夹,不覆盖原图
使用步骤
- 在代码同级新建
images文件夹,把所有原图放进去 - 修改顶部配置:尺寸、文件名前缀、目标格式、水印文字
- 直接运行脚本,处理完成的图片自动保存在
output,原图不受影响
完整代码
import os
from PIL import Image, ImageDraw, ImageFont
# ===================== 配置项(可自行修改)=====================
# 源文件夹与输出文件夹
SRC_FOLDER = "./images"
OUT_FOLDER = "./output"
# 统一图片尺寸 宽,高
TARGET_SIZE = (800, 600)
# 重命名配置:前缀+序号
NAME_PREFIX = "photo"
START_NUM = 1
# 格式转换:可选 "jpg", "png", "webp"
TARGET_FORMAT = "jpg"
# 水印文字
WATER_TEXT = "版权所有"
WATER_COLOR = (255, 0, 0) # 红色
FONT_SIZE = 30
# ==============================================================
def create_folder():
"""不存在文件夹则自动创建"""
if not os.path.exists(SRC_FOLDER):
os.mkdir(SRC_FOLDER)
if not os.path.exists(OUT_FOLDER):
os.mkdir(OUT_FOLDER)
def get_image_files():
"""遍历文件夹,只读取图片文件"""
img_ext = [".jpg", ".jpeg", ".png", ".bmp", ".webp"]
file_list = []
for file in os.listdir(SRC_FOLDER):
ext = os.path.splitext(file)[1].lower()
if ext in img_ext:
file_list.append(os.path.join(SRC_FOLDER, file))
return file_list
def add_watermark(img):
"""给图片添加文字水印"""
draw = ImageDraw.Draw(img)
try:
font = ImageFont.truetype("simhei.ttf", FONT_SIZE)
except:
font = ImageFont.load_default()
w, h = img.size
# 水印放在右下角
draw.text((w - 200, h - 50), WATER_TEXT, fill=WATER_COLOR, font=font)
return img
def batch_process():
create_folder()
img_files = get_image_files()
if len(img_files) == 0:
print("【提示】images文件夹内没有找到图片!")
return
index = START_NUM
for file_path in img_files:
try:
# 打开图片
im = Image.open(file_path)
# 1. 修改尺寸
im = im.resize(TARGET_SIZE, Image.Resampling.LANCZOS)
# 2. 添加水印
im = add_watermark(im)
if TARGET_FORMAT.lower() == "jpg":
if im.mode == "RGBA":
white_bg = Image.new("RGB", im.size, (255, 255, 255))
white_bg.paste(im, mask=im.split()[3])
im = white_bg
# 新文件名
new_name = f"{NAME_PREFIX}_{index:03d}.{TARGET_FORMAT}"
save_path = os.path.join(OUT_FOLDER, new_name)
# 区分格式保存参数,png不需要quality
if TARGET_FORMAT.lower() == "jpg":
im.save(save_path, quality=85)
else:
im.save(save_path)
print(f"已处理:{os.path.basename(file_path)} → {new_name}")
index += 1
except Exception as e:
print(f"处理失败 {file_path},错误:{e}")
if __name__ == "__main__":
print("===== 批量图片处理工具 =====")
batch_process()
print("\n全部任务执行完毕,请到output文件夹查看结果!")知识扩展
下面是一个基于 Python 的批量图片处理工具,支持调整大小、格式转换、旋转、添加水印等常见操作。该工具使用 Pillow 库处理图片,通过命令行参数灵活控制。
功能特性
- 调整尺寸:按固定宽高或百分比缩放,保持比例。
- 格式转换:支持 JPG、PNG、WebP 等格式互转。
- 旋转:按指定角度旋转图片。
- 添加水印:支持文本水印或图片水印(透明叠加)。
- 重命名/导出:可指定输出目录,保持原文件名或添加后缀。
- 递归处理:可处理子目录中的所有图片。
环境准备
pip install Pillow
完整代码
import os
import argparse
from PIL import Image, ImageDraw, ImageFont
SUPPORTED_FORMATS = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp')
def process_image(input_path, output_path, options):
"""处理单张图片"""
try:
img = Image.open(input_path)
# 旋转
if options.rotate:
img = img.rotate(options.rotate, expand=True)
# 调整尺寸
if options.resize or options.scale:
if options.resize:
width, height = map(int, options.resize.split('x'))
img = img.resize((width, height), Image.Resampling.LANCZOS)
elif options.scale:
scale = float(options.scale)
new_size = (int(img.width * scale), int(img.height * scale))
img = img.resize(new_size, Image.Resampling.LANCZOS)
# 格式转换(根据输出后缀决定)
ext = os.path.splitext(output_path)[1].lower()
if ext in ('.jpg', '.jpeg'):
img = img.convert('RGB') # JPG 不支持透明度
# 添加水印(文字或图片)
if options.watermark_text:
img = add_text_watermark(img, options.watermark_text)
if options.watermark_image:
img = add_image_watermark(img, options.watermark_image)
img.save(output_path, quality=options.quality if ext in ('.jpg', '.jpeg', '.webp') else 100)
return True
except Exception as e:
print(f"处理失败 {input_path}: {e}")
return False
def add_text_watermark(img, text):
"""添加文字水印"""
draw = ImageDraw.Draw(img)
font_size = int(min(img.width, img.height) * 0.05) # 根据图片尺寸自适应
try:
font = ImageFont.truetype("arial.ttf", font_size)
except:
font = ImageFont.load_default()
bbox = draw.textbbox((0, 0), text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
x = (img.width - text_width) // 2
y = img.height - text_height - 20
draw.text((x, y), text, font=font, fill=(255,255,255,128))
return img
def add_image_watermark(img, watermark_path):
"""添加图片水印(叠加)"""
if not os.path.exists(watermark_path):
return img
wm = Image.open(watermark_path).convert("RGBA")
# 缩放水印至原图宽度的 20%
scale = 0.2
new_w = int(img.width * scale)
wm = wm.resize((new_w, int(wm.height * (new_w / wm.width))), Image.Resampling.LANCZOS)
# 贴到右下角
x = img.width - wm.width - 20
y = img.height - wm.height - 20
if img.mode != 'RGBA':
img = img.convert('RGBA')
img.paste(wm, (x, y), wm) # 使用 alpha 通道作为蒙版
return img
def collect_images(root_dir, recursive):
"""收集所有图片文件路径"""
images = []
if os.path.isfile(root_dir):
return [root_dir]
for entry in os.scandir(root_dir):
if entry.is_file() and entry.name.lower().endswith(SUPPORTED_FORMATS):
images.append(entry.path)
elif recursive and entry.is_dir():
images.extend(collect_images(entry.path, recursive))
return images
def main():
parser = argparse.ArgumentParser(description="批量图片处理工具")
parser.add_argument("input", help="输入文件或目录")
parser.add_argument("-o", "--output", default="./output", help="输出目录 (默认 ./output)")
parser.add_argument("-r", "--recursive", action="store_true", help="递归处理子目录")
parser.add_argument("--resize", help="调整尺寸,格式: 800x600")
parser.add_argument("--scale", help="缩放比例,如 0.5 表示缩小一半")
parser.add_argument("--rotate", type=float, help="旋转角度(度)")
parser.add_argument("--format", help="输出格式,如 jpg, png, webp")
parser.add_argument("--watermark-text", help="添加文字水印")
parser.add_argument("--watermark-image", help="添加图片水印")
parser.add_argument("--quality", type=int, default=85, help="JPEG/WebP 质量 (1-100), 默认 85")
parser.add_argument("--suffix", default="_processed", help="输出文件名后缀")
args = parser.parse_args()
# 收集输入图片
images = collect_images(args.input, args.recursive)
if not images:
print("未找到任何图片")
return
# 创建输出目录
os.makedirs(args.output, exist_ok=True)
# 处理每张图片
for idx, img_path in enumerate(images, 1):
base = os.path.basename(img_path)
name, ext = os.path.splitext(base)
# 确定输出文件名
if args.format:
out_ext = '.' + args.format.lstrip('.')
else:
out_ext = ext
out_name = f"{name}{args.suffix}{out_ext}"
out_path = os.path.join(args.output, out_name)
# 处理
success = process_image(img_path, out_path, args)
print(f"[{idx}/{len(images)}] {base} -> {'成功' if success else '失败'}")
print("全部处理完成!")
if __name__ == "__main__":
main()注意事项
- 水印图片需为 PNG 格式以保留透明度。
- 文字水印会使用系统字体
arial.ttf,如缺失则使用默认字体。 - 处理大量图片时,建议先在小范围测试。
扩展建议
- 增加多线程支持,提高处理速度。
- 支持 EXIF 信息保留。
- 支持自定义水印位置。
- 增加裁剪、滤镜等高级操作。
到此这篇关于基于Python编写一个批量图片处理工具的文章就介绍到这了,更多相关Python图片处理内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
python实现自动化报表功能(Oracle/plsql/Excel/多线程)
这篇文章主要介绍了python实现自动化报表(Oracle/plsql/Excel/多线程)的相关知识,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下2019-12-12


最新评论