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文件夹查看结果!")