PIL how to scale text size in relation to the size of the image

前端 未结 3 1852
Happy的楠姐
Happy的楠姐 2020-12-04 19:45

I\'m trying to dynamically scale text to be placed on images of varying but known dimensions. The text will be applied as a watermark. Is there any way to scale the text in

3条回答
  •  情书的邮戳
    2020-12-04 19:57

    I know this is an old question that has already been answered with a solution that I too have used. Thanks, @Paul!

    Though with increasing the font size by one for each iteration can be time-consuming (at least for me on my poor little server). So eg. small text (like "Foo") would take around 1 - 2 seconds, depending on the image size.

    To solve that I adjusted Pauls code so that it searches for the number somewhat like a binary search.

    breakpoint = img_fraction * photo.size[0]
    jumpsize = 75
    while True:
        if font.getsize(text)[0] < breakpoint:
            fontsize += jumpsize
        else:
            jumpsize = jumpsize // 2
            fontsize -= jumpsize
        font = ImageFont.truetype(font_path, fontsize)
        if jumpsize <= 1:
            break
    

    Like this, it increases the font size until it's above the breakpoint and from there on out it goes up and down with (cutting the jump size in half with each down) until it has the right size.

    With that, I could reduce the steps from around 200+ to about 10 and so from around 1-2 sec to 0.04 to 0.08 sec.

    This is a drop-in replacement for Pauls code (for the while statement and the 2 lines after it because you already get the font correct font size in the while)

    This was done in a few mins so any improvements are appreciated! I hope this can help some who are looking for a bit more performant friendly solution.

提交回复
热议问题