PIL-如何在文本中插入索引或下标?

时间:2018-08-22 06:17:24

标签: python-2.7 python-imaging-library

赞: enter image description here

计算坐标看起来不太好,也许有更好的方法吗?

此代码可以正常工作(enter image description here),但总是计算每个字母的索引位置很复杂。

image = Image.new('I', (300, 100), "white").convert('RGBA')
font = ImageFont.truetype(font=r"C:\Windows\Fonts\Arial.ttf", size=39)
draw = ImageDraw.Draw(image, 'RGBA')

draw.text((10, 10), "P", fill="black", font=font, align="center")

font = ImageFont.truetype(font=r"C:\Windows\Fonts\Arial.ttf", size=20)
draw.text((25, 35), "2", fill="black", font=font, align="center")

image.save(output_folder + 'test.png')

1 个答案:

答案 0 :(得分:0)

您还可以在Matplotlib中使用Mathtext进行此类操作:

#!/usr/bin/env python3

import matplotlib.pyplot as plt

plt.axes([0.025, 0.025, 0.95, 0.95])

# Some formula with superscripts, subscripts, square roots, fractions and integrals
eq    = r"$ 2P_2 O_5 + H^{2j}$"
size  = 50
x,y   = 0.5, 0.5
alpha = 1
params = {'mathtext.default': 'regular' }
plt.rcParams.update(params)
plt.text(x, y, eq, ha='center', va='center', color="#11557c", alpha=alpha,
         transform=plt.gca().transAxes, fontsize=size, clip_on=True)

# Suppress ticks
plt.xticks(())
plt.yticks(())

# Save on transparent background
plt.savefig('result.png', transparent=True)

enter image description here

您还可以将输出保存在内存缓冲区中(不存入磁盘),然后将其用于基于PIL的图像处理中。

请注意,我已经明确命名并分配了所有参数(xysizealpha),因此您可以使用它们,从而完成代码看起来比实际更长,更复杂。

关键字:Python,PIL,Pillow,数学,数学符号,带上标,下标,平方根,分数和整数的公式。