女友論文圖片需加「白底黑框圓圈 + 字母序號」水印,常規軟件難對齊,PS 動作繁瑣。本文展示用 Pillow (PIL fork) 幾十行代碼實現批量自動化,含字符居中微調、圓形繪制、字體加載等實戰技巧。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, fnmatch
from PIL import Image, ImageDraw, ImageFont
# 字母微調偏移(手動測得,不同字體可能不同)
OFFSETS = {'A': 1, 'B': 1, 'E': 1, 'D': 2}
def process_picture(filename, input_dir, output_dir):
seq = os.path.split(filename)[-1][0].upper() # 取文件名首字母作序號
img = Image.open(os.path.join(input_dir, filename))
draw = ImageDraw.Draw(img)
# 1. 畫圓:右下角 (215,215) 到 (235,235),白底黑框
draw.ellipse((215, 215, 235, 235), outline='black', fill='white')
# 2. 字體與文字尺寸
font = ImageFont.truetype('fonts/Times New Roman.ttf', 20)
text_size = draw.textsize(seq, font=font)
# 3. 計算圓心居中坐標(圓寬高 20px)
x = (20 - text_size[0]) / 2
y = (20 - text_size[1]) / 2
# 4. 應用字符級偏移
offset = OFFSETS.get(seq, 0)
draw.text((215 + x + offset, 215 + y), seq, font=font, fill='black')
# 5. 保存
img.save(os.path.join(output_dir, filename), 'JPEG')
if __name__ == '__main__':
if len(sys.argv) < 3:
print('Usage: python drawseq.py ')
sys.exit(1)
input_dir, output_dir = sys.argv[1:3]
os.makedirs(output_dir, exist_ok=True)
for filename in os.listdir(input_dir):
if fnmatch.fnmatch(filename.lower(), '*.jpg'):
process_picture(filename, input_dir, output_dir)
draw.ellipse(bbox, outline, fill),bbox 為外接矩形。textsize() 獲取寬高,結合目標區域幾何中心計算左上角坐標。OFFSETS 補正。fonts/Times New Roman.ttf 需放在腳本同級目錄,或用系統絕對路徑。fnmatch.fnmatch(filename.lower(), '*.jpg') 大小寫不敏感匹配。aggdraw 繪制抗鋸齒圓形(安裝較麻煩,本例放棄)。multiprocessing.Pool 加速大批量圖片。幾十行代碼解決人工繁瑣任務,這就是 Python 自動化辦公的魅力所在。