draw_img_text.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
# draw_img_text.py
#
# Oct/02/2018
#
# ------------------------------------------------------------------
import sys
import numpy
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont
# ------------------------------------------------------------------
def draw_text_proc(img,text,pos):
draw = PIL.ImageDraw.Draw(img)
font_ttf = "/usr/share/fonts/OTF/TakaoPMincho.ttf"
draw.font = PIL.ImageFont.truetype(font_ttf, 10)
img_size = numpy.array(img.size)
txt_size = numpy.array(draw.font.getsize(text))
color = (0,0,255)
draw.text(pos, text, color)
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
file_in = sys.argv[1]
file_out = sys.argv[2]
sys.stderr.write(file_in + "\n")
sys.stderr.write(file_out + "\n")
#
img_base = PIL.Image.open(file_in)
#
text = "Oct/2/2018"
pos = (100,20)
draw_text_proc(img_base, text,pos)
text = "こんにちは"
pos = (100,35)
draw_text_proc(img_base, text,pos)
img_base.show()
img_base.save(file_out)
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------
実行方法
./draw_img_text.py in01.png out01.png
次のバージョンで確認しました。
$ python
Python 3.9.1 (default, Feb 6 2021, 06:49:13)
>>> import PIL
>>> PIL.__version__
'8.1.0'