Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python PIL: font weight and style

On my computer I have only one file for Ubuntu Condensed font, it seems. Namely:

/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf 

However, in LibreOffice I can make this font bold and italic: enter image description here

On Ubuntu font tester web page I can also set different font weights (namely, regular and bold) and different font styles (namely, normal and italic) for the Ubuntu Condensed family. In CSS this might translate to:

/* CSS for bold and italic Ubuntu Condensed font */
font-family: Ubuntu Condensed;
font-style: italic;
font-weight: 700;

Or:

/* CSS for regular and normal Ubuntu Condensed font */
font-family: Ubuntu Condensed;
font-style: normal;
font-weight: 400;

However, when it comes to Python's PIL/Pillow, I couldn't find any working option in ImageFont that would modify the font's style and/or weight other than load different font files with ImageFont.truetype() function.

For the "regular" Ubuntu font (not Condensed) I could load one of the four separate files to get normal, bold, italic and bold+italic styles in Python:

/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-R.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-RI.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-B.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-BI.ttf

But not for Ubuntu Condensed.

So the question is, is it possible to draw an image with bold and/or italic Ubuntu Condensed font in PIL/Pillow? Or is it possible, at least, to generate four Ubuntu Condensed files, so that it can be used like the Ubuntu font from Python?

like image 778
Andriy Makukha Avatar asked Jan 15 '18 07:01

Andriy Makukha


1 Answers

You can select the font-variant you want using the method set_variation_by_name.

In order to get all the variants use the method get_variation_names which should give you a list of names.

>>> from PIL import ImageFont
>>> 
>>> font = ImageFont.truetype(...)
>>> font.get_variation_names()
[b'Normal', b'Bold', b'Italic', b'Bold, Italic']
>>> font.set_variation_by_name('Italic')

This should give you the desired font variant.

like image 136
Friedrich Avatar answered Sep 27 '22 22:09

Friedrich