schemagen/mcdraw.py

34 lines
1.5 KiB
Python
Raw Normal View History

2021-09-30 13:18:38 +08:00
from PIL import ImageFont, Image, ImageDraw
import re
try:
font = ImageFont.truetype("wqy-zenhei.ttc", 24, 1)
emfont = ImageFont.truetype("NotoEmoji-Regular.ttf", 24, 0)
except OSError:
print("Please download these fonts to the current dir:\n"
"wqy-zenhei.ttc\n\tfrom https://downloads.sourceforge.net/project/wqy/wqy-zenhei/0.9.45%20%28Fighting-state%20RC1%29/wqy-zenhei-0.9.45.tar.gz"
"\n"
"NotoEmoji-Regular.ttf\n\tfrom https://github.com/googlefonts/noto-emoji/raw/2f1ffdd6fbbd05d6f382138a3d3adcd89c5ce800/fonts/NotoEmoji-Regular.ttf"
"\n\n"
)
raise
def text_to_im(text="紧密团结在鱼塔同志周围"):
emoji = re.compile("^[" u"\U0001F600-\U0001F64F" u"\U0001F300-\U0001F5FF" u"\U0001F680-\U0001F6FF" u"\U0001F1E0-\U0001F1FF" "]$", flags=re.UNICODE)
brush_location = [0]
def draw_single_char(ch, draw=None):
m = emoji.match(ch)
myfont = emfont if m else font
width = myfont.getsize(ch)[0]
if draw:
draw.text((brush_location[0], -2 if m else 0), ch, fill="black", font=myfont, spacing=0)
brush_location[0] += width
return width
def max_height(text):
return max(*[font.getsize(ch)[1] for ch in text], *[emfont.getsize(ch)[1] for ch in text])
width, height = sum(draw_single_char(ch) for ch in text), max_height(text)
im = Image.new('1', (width, height), color="white")
draw = ImageDraw.Draw(im)
for ch in text:
draw_single_char(ch, draw)
return im