【问题标题】:Breaking Up Long Text Using Pillow使用 Pillow 分解长文本
【发布时间】:2021-09-29 06:47:50
【问题描述】:

默认情况下,在编写文本时,Python 中的 Pillow 返回从侧面截断的文本。我想让它从最后一个单词中截断文本,即自动换行。

当前:

预期:

我发现this 很有用,但它会破坏最后一个字母而不是单词的文本。

【问题讨论】:

    标签: python image text python-imaging-library word-wrap


    【解决方案1】:

    这是我的代码,用于演示如何从长字符串中拆分单词,但仅使用左对齐,并且有/没有边缘对齐。您可以更改以下代码以使其具有中心对齐方式,以及沿边缘的填充数。

    from PIL import Image, ImageDraw, ImageFont
    
    def split(string):
        return string.split()
    
    def draw_text(string, font="cour.ttf", size=16, width=320, height=240,
            background=(255, 255, 255, 0), color='black', edge=False,
            justification='center', mode="RGBA"):
    
        im = Image.new(mode=mode, size=(width, height), color=background)
        draw = ImageDraw.Draw(im, mode)
        font = ImageFont.truetype(font=font, size=size)
    
        words = split(string)
        length = len(words)
        lines, start = [], 0
    
        for i in range(length):
            line = ' '.join(words[start:i+1])
            w, h = font.getsize(line)
            if (w > width):
                lines.append(' '.join(words[start:i]))
                start = i
            elif i == length-1:
                lines.append(line)
    
        len_lines = len(lines)
        dy = (height-h)//(len_lines-1)
        for i, line in enumerate(lines):
            if edge and (i != len_lines-1):
                words = line.split()
                length = len(words)
                delta = (width - sum(map(lambda x:font.getsize(x)[0], words)))//(length-1) if length>1 else 0
                x = 0
                for j, word in enumerate(words):
                    draw.text((x, i*dy), word, fill=color, font=font)
                    x += font.getsize(word)[0]+delta
            else:
                draw.text((0, i*dy), line, fill=color, font=font)
    
        im.show()    # using im.save to save image to file
    
    width, height = 960, 120
    font, size = "arial.ttf", 32
    align = True
    string = (
        "Python is an easy to learn, powerful programming language. "
        "It has efficient high-level data structures and a simple "
        "but effective approach to object-oriented programming.").strip()
    
    draw_text(string, font=font, size=size, width=width, height=height, edge=True)
    draw_text(string, font=font, size=size, width=width, height=height, edge=False)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多