Skip to content

Instantly share code, notes, and snippets.

@bornfree
Last active April 22, 2023 19:42
Show Gist options
  • Save bornfree/d657a2b0975870f98680073caa582ace to your computer and use it in GitHub Desktop.
Save bornfree/d657a2b0975870f98680073caa582ace to your computer and use it in GitHub Desktop.
Generate an image using TTF font with PIL (pillow)
from PIL import Image, ImageFont, ImageDraw
FONT_SIZE = 40
MAX_PADDING = 4
font_path = "~/Downloads/Roboto.ttf"
font_object = ImageFont.truetype(font_path, FONT_SIZE) # Font has to be a .ttf file
word = "hello"
fg = "#000000" # black foreground
bg = "#FFFFFF" # white background
text_width, text_height = font_object.getsize(word)
image = Image.new('RGBA', (text_width + MAX_PADDING*2, text_height + MAX_PADDING*2), color=bg)
draw_pad = ImageDraw.Draw(image)
draw_pad.text((MAX_PADDING, MAX_PADDING-6), word, font=font_object, fill=fg)
file_name = "output.png"
# image = image.convert("L") # Use this if you want to binarize image
image.save(file_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment