PIL
python3

PIL で日本語の文字を書く

ツルータイプのフォントを使って PIL で画像を作成しました。

out01.png

draw_text.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   draw_text.py
#
#                   Mar/20/2018
#
# ------------------------------------------------------------------
import sys
import numpy

import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont

# ------------------------------------------------------------------
def draw_text_at_center(img, text):
    draw = PIL.ImageDraw.Draw(img)
    font_ttf = "/usr/share/fonts/OTF/TakaoPMincho.ttf"
    draw.font = PIL.ImageFont.truetype(font_ttf, 80)

    img_size = numpy.array(img.size)
    txt_size = numpy.array(draw.font.getsize(text))
    pos = (img_size - txt_size) / 2

    draw.text(pos, text, (0, 0, 255))

# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
img = PIL.Image.new("RGBA", (400, 300))
text = "こんにちは"
draw_text_at_center(img, text)
img.show()
filename = "out01.png"
img.save(filename)
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------