Add Text on Image using PIL

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

    I think ImageFont module available in PIL should be helpful in solving text font size problem. Just check what font type and size is appropriate for you and use following function to change font values.

    # font = ImageFont.truetype(, )
    # font-file should be present in provided path.
    font = ImageFont.truetype("sans-serif.ttf", 16)
    

    So your code will look something similar to:

    from PIL import Image
    from PIL import ImageFont
    from PIL import ImageDraw 
    
    img = Image.open("sample_in.jpg")
    draw = ImageDraw.Draw(img)
    # font = ImageFont.truetype(, )
    font = ImageFont.truetype("sans-serif.ttf", 16)
    # draw.text((x, y),"Sample Text",(r,g,b))
    draw.text((0, 0),"Sample Text",(255,255,255),font=font)
    img.save('sample-out.jpg')
    

    You might need to put some extra effort to calculate font size. In case you want to change it based on amount of text user has provided in TextArea.

    To add text wrapping (Multiline thing) just take a rough idea of how many characters can come in one line, Then you can probably write a pre-pprocessing function for your Text, Which basically finds the character which will be last in each line and converts white space before this character to new-line.

提交回复
热议问题