🙃

【Slack絵文字】気軽に文字だけのgifをつくりたい

2021/03/20に公開

Slackの絵文字用に文字だけのgifを気軽に作りたいという話があったので試しに作ってみた。
(話題にあがったものが横にまわる系だったのでそれにフォーカスしてます)

こんな感じイメージ1イメージ2

仕様

  • 追加可能なサイズ: 128 * 128
  • フォントは利用したいttfやotfのpathを指定
  • フォント・背景色の色、まわる速さはお好みで
  • 日本語でいくつかのフォントを試すと、下が切れる場合があったのでちょっとだけ高さは下に合わせている

やっていることは、①文字の長さ(px)を確認して、②長さに合わせてコマ送りに描画した画像を作り、まとめているだけ。
文字の長さは実際に描画してみないとわからないのでdummyで一度描画して幅を出している。

文頭と文末の文字をつなげないパターン.py
from PIL import Image, ImageDraw, ImageFont

# 好みの部分
text = 'ながれる絵文字'
font_color = 'black'
background_color = 'white'
font_path = './hoge.ttf'
speed = 20

canvas_size = (128, 128)
font_size = 128
font = ImageFont.truetype(font_path, font_size)

# dummy for get text_size
tmp = Image.new('RGB', (1, 1), "black")
tmp_d = ImageDraw.Draw(tmp)
text_w, text_h = tmp_d.textsize(text, font)

images =[]

start = 128
end = (text_w + 128) * -1
h = 126 - text_h
s = speed * -1
    
for x_start in range(start,end,s):
    img = Image.new('RGB', canvas_size, background_color)
    draw = ImageDraw.Draw(img)
    draw.text((x_start, h), text, fill=font_color, font=font)
    images.append(img)

images[0].save('out.gif',save_all=True,append_images=images[1:],optimize=False,duration=50,loop=0)
文頭と文末の文字をつなげるパターン.py
from PIL import Image, ImageDraw, ImageFont

# 好みの部分
text = 'ぐるぐる'
font_color = 'black'
background_color = 'white'
font_path = './hoge.ttf'
speed = 20

canvas_size = (128, 128)
font_size = 128
font = ImageFont.truetype(font_path, font_size)

# dummy for get text_size
tmp = Image.new('RGB', (1, 1), "black")
tmp_d = ImageDraw.Draw(tmp)
text_w, text_h = tmp_d.textsize(text, font)

images =[]

start = 0
end = text_w * -1
h = 126 - text_h
s = speed * -1    
repeat = text * ((128 // text_w) + 1) * 2

for x_start in range(start,end,s):
    img = Image.new('RGB', canvas_size, background_color)
    draw = ImageDraw.Draw(img)
    draw.text((x_start, h), repeat, fill=font_color, font=font)
    images.append(img)

images[0].save('out.gif',save_all=True,append_images=images[1:],optimize=False,duration=50,loop=0)

もっといい方法があったら教えてください

Discussion