LoginSignup
0
0

More than 1 year has passed since last update.

pillow で テキストを画像に変換

Last updated at Posted at 2018-11-26

Arch Linux で必要なライブラリーをインストール

sudo pacman -S python-reportlab
yay otf-takao

プログラム

text_to_png.py
#! /usr/bin/python
#
#	text_to_png.py
#
#					Mar/24/2023
#
# ------------------------------------------------------------------
import sys
from PIL import Image, ImageDraw, ImageFont
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
# ------------------------------------------------------------------
def text_to_png_proc(lines_in,png_out):
	height = 16
#	width = 1200
	width = 100
#
	lines_out = limit_length_proc(lines_in)
	llx = len(lines_out)
	sys.stderr.write("llx = %d\n" % llx)
	yy_height = height * llx + 50
	sys.stderr.write("yy_height = %d\n" % yy_height)
	text_canvas = Image.new('RGB', (width, yy_height), (255, 255, 255))
	draw = ImageDraw.Draw(text_canvas)
#
	font_ttf = "/usr/share/fonts/OTF/TakaoPMincho.ttf"
	draw.font = ImageFont.truetype(font_ttf, height)
#	
	font_ttf = "/usr/share/fonts/OTF/TakaoPMincho.ttf"
	draw.font = ImageFont.truetype(font_ttf, height)
#
	xx = 20
	yy = 20
	color = (0,0,0)
	for line in lines_out:
		pos = (xx,yy)
		draw.text(pos, line, color)
		yy += height
#
#	text_canvas.show()
	text_canvas.save(png_out)
# ------------------------------------------------------------------
def limit_length_proc(lines_in):
	lines_out = []
	for line in lines_in:
		if len(line) <= 80:
			lines_out.append(line)
		elif len(line) <= 160:
			lines_out.append(line[:80])
			lines_out.append(line[80:])
		else:
			lines_out.append(line[:80])
			lines_out.append(line[80:160])
			lines_out.append(line[160:])
#
	return lines_out
# ------------------------------------------------------------------

使用方法

./text_to_png.py in01.txt out01.png
in01.txt
AAA

out01.png
out01.png

確認したバージョン

$ python --version
Python 3.10.10
0
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
0
0