Add Text on Image using PIL

后端 未结 8 1242
后悔当初
后悔当初 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:37

    First, you have to download a font type...for example: https://www.wfonts.com/font/microsoft-sans-serif.

    After that, use this code to draw the text:

    from PIL import Image
    from PIL import ImageFont
    from PIL import ImageDraw 
    img = Image.open("filename.jpg")
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype(r'filepath\..\sans-serif.ttf', 16)
    draw.text((0, 0),"Draw This Text",(0,0,0),font=font) # this will draw text with Blackcolor and 16 size
    
    img.save('sample-out.jpg')
    
    0 讨论(0)
  • 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)) 
    
    0 讨论(0)
提交回复
热议问题