Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make to make text size auto adjust to an image with PIL

I am trying to get some text to overlap on an image, which is I have the following code for.

from PIL import Image, ImageDraw, ImageFont

msg = "This is a test phrase, so please shrink the text."

im = Image.open("test.jpg")
draw = ImageDraw.Draw(im)

W, H = im.size

myFont =             
ImageFont.truetype("/usr/share/fonts/truetype/customfonts/KeepCalm-Medium.ttf")

w, h = draw.textsize(msg, font=myFont)
draw.text(((W-w)/2,(H-h)/2), msg, fill="black", font=myFont)

im.save("sample-out.png", "PNG")

What I need is the text to scale in the middle, but between the pixel width and height of 1600,300. Whichever one it achieve first.

I imagine it has something to do with fontsize increasing, but I can't figure it out.

like image 606
Luke Appel Avatar asked Jan 04 '19 00:01

Luke Appel


1 Answers

So figured it out with a bit of luck, here is the below code. Please note that some variables changed names from the original code above, but this works.

from PIL import ImageFont, ImageDraw, Image

image = Image.open('test.jpg')
draw = ImageDraw.Draw(image)
txt = "share/fonts/truetype/customfonts/KeepC"
fontsize = 1  # starting font size

W, H = image.size

# portion of image width you want text width to be
blank = Image.new('RGB',(1000, 300))


font = ImageFont.truetype("/usr/share/fonts/truetype/customfonts/KeepCalm-Medium.ttf", fontsize)
print image.size
print blank.size

while (font.getsize(txt)[0] < blank.size[0]) and (font.getsize(txt)[1] < blank.size[1]):
    # iterate until the text size is just larger than the criteria
    fontsize += 1
    font = ImageFont.truetype("/usr/share/fonts/truetype/customfonts/KeepCalm-Medium.ttf", fontsize)

# optionally de-increment to be sure it is less than criteria
fontsize -= 1
font = ImageFont.truetype("/usr/share/fonts/truetype/customfonts/KeepCalm-Medium.ttf", fontsize)

w, h = draw.textsize(txt, font=font)

print 'final font size',fontsize
draw.text(((W-w)/2,(H-h)/2), txt, font=font, fill="black") # put the text on the image
image.save('sample-out.png') # save it
like image 52
Luke Appel Avatar answered Sep 20 '22 06:09

Luke Appel