简体   繁体   中英

Text using PIL on Python

I am trying to use the PIL module and ImageDraw to add text on an image. I want to add this text at a given absciss but I want to use 2 different fonts. The problem is that I do not manage to use 2 types of front in the draw.text. To imagine the situation I want to obtain something as in the following photo with 2 different fonts in the same display. Do you have some ideas?

在此处输入图像描述

You can load and reference different fonts in PIL using

font1 = ImageFont.truetype("/usr/share/fonts/gnu-free/FreeMono.otf", size=20)
font2 = ImageFont.truetype("/usr/share/fonts/gnu-free/FreeMono.otf", size=25)

and use it in a single draw call like

draw.text((5, 5), "Hello", font=font1)

You can use font1.getsize("Text contents") or font1.getsize_multiline("Multiline \n text") in order to find out how much space you need to render the text with that font. Using this, you should be able to continue with the new font at that offset. Doing this is not very ergonomic, and probably has a lot of edge cases that need to be handled.

You might be better off with a different library that can render markup text. Perhaps something like pango or cairo, or even LaTeX if you want it to be fancy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM