Python中用PIL庫批量給圖片加上序號的教程

來源:互聯網
上載者:User
女友讓我給她論文的圖片上加上字母序號,本來覺得是個很簡單的事情,但那個白底黑字的圓圈序號卻難住了我, 試了幾個常用的軟體,都不行。

後來用 PS + 動作,倒是能搞出來,不過也不容易,正好那天沒搞完,於是拿回自己家做,但我的電腦上又沒有 PS, 所以就用 python 實現了。


這裡用的圖片全是 240X240 的,按檔案名稱的首字母作為序號,PIL 雖然可以計算文字的尺寸,但類似 D 這樣的字元依然不能處於圓圈的正中,所以還對個別字元做了位移設定,本來想用 aggdraw 畫圓圈的,能平滑 一些,不過安裝了好幾次,都以失敗告終,最終放棄。

#!/usr/bin/env python#-*- coding: utf-8 -*-import os, sys, fnmatchimport Image, ImageDraw, ImageFontdef process_picture(filename):  seq = os.path.split(filename)[-1][0].upper()  img = Image.open(os.path.join(input_dir, filename))  draw = ImageDraw.Draw(img)  # 在右下角畫白底黑框圓圈  draw.ellipse((215, 215, 235, 235), outline='black', fill='white')  # 將字母序號寫入到圓圈內  font = ImageFont.truetype('fonts/Times New Roman.ttf', 20)  # 計算文字置中的位置  text_size = draw.textsize(seq, font)  x = (20 / 2) - (text_size[0] / 2)  y = (20 / 2) - (text_size[1] / 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')  # save image  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.path.exists(output_dir) or os.makedirs(output_dir)  for filename in os.listdir(input_dir):    if fnmatch.fnmatch(filename.lower(), '*.jpg'):      process_picture(filename)
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.