简体   繁体   English

在 Python 上使用 PIL 的文本

[英]Text using PIL on Python

I am trying to use the PIL module and ImageDraw to add text on an image.我正在尝试使用 PIL 模块和 ImageDraw 在图像上添加文本。 I want to add this text at a given absciss but I want to use 2 different fonts.我想在给定的横坐标处添加此文本,但我想使用 2 个不同的 fonts。 The problem is that I do not manage to use 2 types of front in the draw.text.问题是我没有设法在 draw.text 中使用 2 种类型的前端。 To imagine the situation I want to obtain something as in the following photo with 2 different fonts in the same display.想象一下这种情况,我想在同一个显示器中使用 2 个不同的 fonts 获得如下图所示的东西。 Do you have some ideas?你有什么想法吗?

在此处输入图像描述

You can load and reference different fonts in PIL using您可以使用 PIL 加载和引用不同的 fonts

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.您可以使用font1.getsize("Text contents")font1.getsize_multiline("Multiline \n text")来找出使用该字体渲染文本需要多少空间。 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.也许像 pango 或 cairo,甚至 LaTeX 如果你想要它花哨的话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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