Wrap text in PIL

前端 未结 5 929
太阳男子
太阳男子 2020-12-30 03:40

I\'m using PIL to draw text on an image. How would I wrap a string of text. This is my code:

text = \"Lorem ipsum dolor sit amet, consectetur adipisicing eli         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-30 04:31

    Use textwrap. It works without breaking the words.

    import textwrap
    from PIL import *
    caption = "Obama warns far-left candidates says average American does not want to tear down the system"
    
    wrapper = textwrap.TextWrapper(width=50) 
    word_list = wrapper.wrap(text=caption) 
    caption_new = ''
    for ii in word_list[:-1]:
        caption_new = caption_new + ii + '\n'
    caption_new += word_list[-1]
    
    image = Image.open('obama.jpg')
    draw = ImageDraw.Draw(image)
    
    # Download the Font and Replace the font with the font file. 
    font = ImageFont.truetype(text_font, size=font_size)
    w,h = draw.textsize(caption_new, font=font)
    W,H = image.size
    x,y = 0.5*(W-w),0.90*H-h
    
    image.save('output.png')
    

    Input Image

    Output Image

提交回复
热议问题