today 2019-03-05
access_time 1 min
指定したフォントで画像を生成する
日本語が不自由。.ttfを指定して文字を描画しそれをpngファイルで保存する方法について。
Pythonの画像処理についてはOpenCV以外にもPillow等優秀なものが揃っている。今回はPillowのImageFont, ImageDrawを使って実装した。
$ pip install pillow
from PIL import Image, ImageDraw, ImageFont
def make_image(font_path, dst_path, text, font_size=32, font_color="white"):
font = ImageFont.truetype(font_path, font_size)
# get fontsize
tmp = Image.new('RGBA', (1, 1), (0, 0, 0, 0)) # dummy for get text_size
tmp_d = ImageDraw.Draw(tmp)
text_size = tmp_d.textsize(text, font)
# draw text
img = Image.new('RGBA', text_size, (0, 0, 0, 0)) # background: transparent
img_d = ImageDraw.Draw(img)
img_d.text((0, 0), text, fill=font_color, font=font)
img.save(dst_path)
make_image("path/to/font.ttf", "dst.png", "Hello Font")
これだけでできる。便利
font = ImageFont.truetype(font_path, font_size)
描画したテキストがどの程度の画像サイズになるか事前に知っている必要があるため、以下コードで事前に把握している。 どこかに静的関数で存在していればこんな変な実装にならなかったような…。
tmp = Image.new('RGBA', (1, 1), (0, 0, 0, 0)) # dummy for get text_size
tmp_d = ImageDraw.Draw(tmp)
text_size = tmp_d.textsize(text, font)
pillow便利。