Skip to content

Instantly share code, notes, and snippets.

@waylan
Last active September 17, 2021 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waylan/cab926393f6db2e201963cc7800bb770 to your computer and use it in GitHub Desktop.
Save waylan/cab926393f6db2e201963cc7800bb770 to your computer and use it in GitHub Desktop.
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 = Image.new('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
else:
break
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)
img.save(fp, format)
if __name__ == '__main__':
create_image('Some text\nLine two\nThe third line which is longer', (200, 100), 'example.png')
@waylan
Copy link
Author

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).

@waylan
Copy link
Author

waylan commented Sep 17, 2021

As of Revision 4, the generated image is:

example

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