Add Text on Image using PIL

后端 未结 8 1292
后悔当初
后悔当初 2020-12-07 08:02

I have an application that loads an Image and when the user clicks it, a text area appears for this Image (using jquery), where user can write some text on the

8条回答
  •  生来不讨喜
    2020-12-07 08:43

    One thing not mentioned in other answers is checking the text size. It is often needed to make sure the text fits the image (e.g. shorten the text if oversized) or to determine location to draw the text (e.g. aligned text top center). Pillow/PIL offers two methods to check the text size, one via ImageFont and one via ImageDraw. As shown below, the font doesn't handle multiple lined, while ImageDraw does.

    In [28]: im = Image.new(mode='RGB',size=(240,240))                                                            
    In [29]: font = ImageFont.truetype('arial')
    In [30]: draw = ImageDraw.Draw(im)
    In [31]: t1 = 'hello world!'
    In [32]: t2 = 'hello \nworld!'
    In [33]: font.getsize(t1), font.getsize(t2) # the height is the same
    Out[33]: ((52, 10), (60, 10)) 
    In [35]: draw.textsize(t1, font), draw.textsize(t2, font)  # handles multi-lined text
    Out[35]: ((52, 10), (27, 24)) 
    

提交回复
热议问题