我使用Pillow在图像上添加一行文字,有时文字可能会超过图像的宽度。在这种情况下,我想用省略号(...)替换额外的字符,以便它可以恰好适合图像。
我正在使用{{1}}。我想知道Pillow是否有自动方式这样做?非常感谢。
答案 0 :(得分:2)
没有内置功能。 但是自己写它并不是那么困难。
创建CustomerViewModel
对象后,您可以使用其getsize
方法查询文本的宽度和高度。
如果长度超过图像宽度,请缩短文本并重试。假设我们的长度为100像素。
ImageFont
所以我们只能用5个字;
In [1]: s = 'this is a text that might be too long.'
In [2]: from PIL import ImageFont
In [4]: font = ImageFont.truetype("/usr/local/share/fonts/local/Komika.ttf")
In [6]: split = s.split(' ')
In [7]: for i in range(len(split)+1):
...: print(i, font.getsize(' '.join(split[:i])+' ...'))
...:
0 (9, 10)
1 (25, 10)
2 (35, 10)
3 (43, 10)
4 (63, 10)
5 (84, 10)
6 (111, 12)
7 (124, 12)
8 (141, 12)
9 (163, 12)