Skip to content

Instantly share code, notes, and snippets.

Last active September 17, 2021 13:22
What would you like to do?
Create an image of text, which is centered both ways. Useful for creating a label.
from PIL import Image, ImageDraw, ImageFont
def create_image(text, size, fp, format=None):
img ='L', size, 'white')
draw = ImageDraw.Draw(img)
# Find largest font size which fits within image size
fontsize = 20
margin = 10
while True:
font = ImageFont.truetype('times.ttf', fontsize)
txtsize = draw.multiline_textsize(text, font=font)
if txtsize[0] >= size[0] - (margin * 2) or txtsize[1] >= size[1] - (margin * 2):
# reduce font size and try again
fontsize -= 2
print(f'Using font size {fontsize} which results in text size of {txtsize}.')
# Center text horizontally and vertically in image.
# Set anchor point to the middle (half width and half height of image size)
# and anchor alignment to middle/middle (mm) of text.
draw.multiline_text((size[0]/2, size[1]/2), text, fill='black', font=font, anchor='mm', align='center')
font8 = ImageFont.truetype('times.ttf', 8)
# Add a line of text to top left corner
draw.text((margin, margin), 'Top Left', fill='black', font=font8, anchor='la', align='left')
# And bottom left corner
draw.text((margin, size[1] - margin), 'Bottom Left', fill='black', font=font8, anchor='ld', align='left')
# And top right corner
draw.text((size[0] - margin, margin), 'Top Right', fill='black', font=font8, anchor='ra', align='right')
# And bottom right corner
draw.text((size[0] - margin, size[1] - margin), 'Bottom Right', fill='black', font=font8, anchor='rd', align='right')
# Outline with rounded rect
draw.rounded_rectangle([(0, 0), (size[0] - 1, size[1] - 1)], radius=10, outline='black', width=1), format)
if __name__ == '__main__':
create_image('Some text\nLine two\nThe third line which is longer', (200, 100), 'example.png')
Copy link

waylan commented Sep 16, 2021

As of Revision 2, the debug output is:

Using font size 14 which results in text size of (166, 47).

Copy link

waylan commented Sep 17, 2021

As of Revision 4, the generated image is:


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment