0
2

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を使って文字列を改行しながら画像へ挿入する

Posted at

1. 本記事について

pillowを使って画像に文字を挿入するときに、四角形のスペースに上手く収まる
フォントサイズの計算+改行を良い塩梅でやってくれるコードです。

※実行結果イメージ
image.png

2. コード

insert_text_to_image.py
# coding:utf-8

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import math

# 吹き出しのサイズ
canbas_height = 130
canbas_width = 350
# 吹き出しの余白
margin = 50
# 文字の挿入位置
height = 203
width = 47
# 行間
space_between_lines = 3
# フォント情報
font_color = (22, 22, 22)
font_path = "/hoge/hoge.ttf"
# 元画像ファイルのパス
base_image_path = "/hoge/base.png"
# 挿入するテキスト
base_text ="おはようございます"
# 保存する画像ファイルのパス
save_image_path = "/hoge/result.png"


# フォントサイズ計算
def culculate_text_size(text):
    text_length = len(text)
    canbas_area_size = (canbas_height - margin)*(canbas_width - margin)
    font_size = math.floor(math.sqrt(canbas_area_size / text_length))

    return font_size

# 改行する単位でテキストをリスト化
def split_text(text, font_size):
    text_length = len(text)
    text_in_one_line = canbas_width // font_size
    text_list = [text[i: i + text_in_one_line] for i in range(0, len(text), text_in_one_line)]

    return text_list

# 画像の指定位置にテキスト追加
def add_text_to_image(img, text, font_size, height):
    position = (width, height)
    font = ImageFont.truetype(font_path, font_size)
    draw = ImageDraw.Draw(img)

    draw.text(position, text, font_color, font=font)

    return img

# テキストのリストを画像に挿入
def insert_split_texts(image, split_text, font_size, height):
    for texts in split_text:
        img = add_text_to_image(image, texts, font_size, height)
        height += (font_size)

    return img

def main():
    base_image = Image.open(base_image_path).copy()
    font_size = culculate_text_size(base_text)
    insert_text = split_text(base_text, font_size)
    img = insert_split_texts(base_image, insert_text, font_size, height)
    img.save(save_image_path)

if __name__ == "__main__":
    main()

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?