How can I set the size of the default font loaded by PIL so it fits on my 8x8 matrix?

user391339 picture user391339 · Nov 23, 2014 · Viewed 7.7k times · Source

I am working on displaying text on an 8x8 matrix display and I don't have a .ttf file handy that I know of on my BeagleBone.

According to an example here, I should be able to say font = ImageFont.load_default() instead of loading a .ttf, but, this is clearly not specifying the dimensions of the font! Any way to do this? Alternatively, is there a place that you know for sure I can find a .ttf font on my BBB version of ubuntu 14.04.1?

import Image
import ImageDraw
import ImageFont

# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
# Load default font.
font = ImageFont.load_default()

# Alternatively load a TTF font.
# Some other nice fonts to try: http://www.dafont.com/bitmap.php
#font = ImageFont.truetype('Minecraftia.ttf', 8)

# Write two lines of text.
draw.text((x, top),    'Hello',  font=font, fill=255)
draw.text((x, top+20), 'World!', font=font, fill=255)

Answer

Josep Valls picture Josep Valls · May 25, 2017

There is no option to select the size of the load_default font because that is a raster font format. If you check inside the code of ImageFont.py it is actually storing the font information right there encoded in base64. Not sure where you can find for sure a font in your distribution, but the best for sure, future-proof way may be to actually do the same and just include font data in your script. See here: PIL's Github Repo

Alternatively, you could just use the built in font, figure out the size and then downsize to the size of your display: http://effbot.org/imagingbook/imagedraw.htm#tag-ImageDraw.Draw.textsize