3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pillow で画像に文字を挿入

Last updated at Posted at 2018-10-02

入力データ
in01.png

出力データ
out01.png

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'
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?