converter.py 文件源码

python
阅读 29 收藏 0 点赞 0 评论 0

项目:paperwaster 作者: Talon876 项目源码 文件源码
def text_to_image(msg, font=None, font_path=None, font_size=24, accurate=True):
    font = font if font else ImageFont.truetype(font_path, font_size)
    wrapper = textwrap.TextWrapper()

    # w is the widest and y is the tallest
    glyph_w, glyph_h = font.getsize('w')[0], font.getsize('y')[1]
    chars_per_line = PRINTER_WIDTH / glyph_w 
    wrapper.width = chars_per_line

    msg_lines = wrapper.wrap(msg)
    # lines may vary in height so loop over all of them when accurate is True
    # otherwise just count each line as the height of a 'y'
    height = sum([font.getsize(h)[1] for h in msg_lines]) if accurate else glyph_h * len(msg_lines)

    img = Image.new('1', (PRINTER_WIDTH, height), color='white')
    draw = ImageDraw.Draw(img)
    y = 0
    for line in msg_lines:
        h = font.getsize(line)[1]
        draw.text([0, y], line, font=font)
        y += h
    return img
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号