首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 使用 Pillow (PIL) 批次為圖片加上字母序號

     編輯:更多程式設計知識

需求:為資料夾內所有 JPG 圖片右下角加上白底黑框圓圈與字母序號(依檔名首字母)。Pillow (PIL) 提供繪圖、字型、圖形功能,可完美實現。本文提供完整腳本與細節處理技巧。

效果預覽

圖片尺寸 240x240,右下角繪製 20x20 圓圈,圓心置入字母,特定字母微調偏移置中。

完整腳本


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, fnmatch
from PIL import Image, ImageDraw, ImageFont

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)

    # 繪製白底黑框圓圈 (右下角 215,215 到 235,235)
    draw.ellipse((215, 215, 235, 235), outline='black', fill='white')

    # 載入字型
    font = ImageFont.truetype('fonts/Times New Roman.ttf', 20)

    # 計算文字置中位置
    text_w, text_h = draw.textsize(seq, font=font)
    x = (20 - text_w) // 2
    y = (20 - text_h) // 2

    # 字母微調偏移
    offsets = {'A': 1, 'B': 1, 'E': 1, 'D': 2}
    offset = offsets.get(seq, 0)

    draw.text((215 + x + offset, 215 + y), seq, font=font, fill='black')

    # 儲存
    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)

關鍵技巧

  • ImageDraw.ellipse 繪製圓形邊框與填滿。
  • textsize 取得文字寬高,計算置中座標。
  • 字型檔案需存在(範例使用 fonts/Times New Roman.ttf),可改用系統字型路徑。
  • 特定字母(如 D)視覺置中需微調,使用字典對映偏移量。
  • fnmatch.fnmatch 大小寫不敏感比對副檔名。

擴展建議

  1. 支援更多圖片格式(PNG, BMP 等)。
  2. 自動調整圓圈大小適應不同解析度圖片。
  3. 使用 aggdraw 獲得抗鋸齒圓圈(需額外安裝)。
  4. 加入多執行緒加速批次處理。

Pillow 功能強大,適合各類影像自動化處理任務。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved