Last Updated on 2020-08-26 by Clay
Introduction
Today, I need to plot font files in PNG format and save it, which sounds like a rare requirement. After browsing on the Internet, I found that it can use ImageFont module of Python package Pillow to solved.
At the beginning, I wanted to use the Python package fontTools to solve the problem, but later I found that the Imagefont module in Pillow was better.
ImageFont module
In the following range, I used Pillow to load Ubuntu.ttf font file that comes with Ubuntu, and tried to print the letter A and place it in the center of the picture.
The following is the example code:
# -*- coding: utf-8 -*-
from PIL import Image, ImageDraw, ImageFont
# Settings
W, H = (224, 224)
# Font
font = ImageFont.truetype("/home/clay/.fonts/Ubuntu.ttf", 224, encoding='utf-8')
# Image
image = Image.new("RGB", (W, H), "black")
draw = ImageDraw.Draw(image)
offset_w, offset_h = font.getoffset("A")
w, h = draw.textsize("A", font=font)
pos = ((W-w-offset_w)/2, (H-h-offset_h)/2)
# Draw
draw.text(pos, "A", "white", font=font)
# Save png file
image.save("test.png")
Output:
There is nothing to explain. Simply put, use Imagefont to load the font file => decided the text to be plot => create the picture => calculate the offset => plot it.
Finally, save the Pillow object in PNG format and it's done.
Reference
- https://github.com/python-pillow/Pillow/issues/2067
- https://pillow.readthedocs.io/en/stable/reference/ImageFont.html
- https://stackoverflow.com/questions/24085996/how-i-can-load-a-font-file-with-pil-imagefont-truetype-without-specifying-the-ab