Python PIL 文本放置居中
Python PIL text placement centering
我有一个格式证书,让我们假设等于:https://elearning.adobe.com/blank-achievement-certificate
下载示例证书并另存为 'certificate.png' 后,我在 Python 上写了一个示例代码,说明我必须执行哪些操作才能自动生成证书:
from PIL import Image, ImageDraw, ImageFont
people = ['Homer Simpson', 'Seymour Skinner', 'Apu Nahasapeemapetilon']
for i in range(len(people)):
img = Image.open('certificate.png')
d = ImageDraw.Draw(img)
d.text((290, 210), people[i], fill = (255, 0, 0), font = ImageFont.truetype("times.ttf", 24))
img.show()
我正在寻找一种方法,使要写入的文本沿 x 轴方向居中,因为根据名称的长度,证书是不可接受的。
PIL.ImageDraw
有一种方法可以获取您要绘制的文本的大小:
draw = ImageDraw.Draw(img)
w, h = draw.textsize("Your Text")
因此,要在中心写点东西,您需要执行以下操作
people = ['Homer Simpson', 'Seymour Skinner', 'Apu Nahasapeemapetilon']
for person in people:
img = Image.open('certificate.png')
# Get the size of the image
W, H = img.size
draw = ImageDraw.Draw(img)
# Get the size of the textbox
w, h = draw.textsize(person)
coords = ((W - w) / 2, (H - h) / 2)
draw.text(coords, person, fill = (255, 0, 0), font = ImageFont.truetype("times.ttf", 24))
img.show()
另请注意,您可以直接迭代 people,而不是迭代 range(len(people))
。
我有一个格式证书,让我们假设等于:https://elearning.adobe.com/blank-achievement-certificate
下载示例证书并另存为 'certificate.png' 后,我在 Python 上写了一个示例代码,说明我必须执行哪些操作才能自动生成证书:
from PIL import Image, ImageDraw, ImageFont
people = ['Homer Simpson', 'Seymour Skinner', 'Apu Nahasapeemapetilon']
for i in range(len(people)):
img = Image.open('certificate.png')
d = ImageDraw.Draw(img)
d.text((290, 210), people[i], fill = (255, 0, 0), font = ImageFont.truetype("times.ttf", 24))
img.show()
我正在寻找一种方法,使要写入的文本沿 x 轴方向居中,因为根据名称的长度,证书是不可接受的。
PIL.ImageDraw
有一种方法可以获取您要绘制的文本的大小:
draw = ImageDraw.Draw(img)
w, h = draw.textsize("Your Text")
因此,要在中心写点东西,您需要执行以下操作
people = ['Homer Simpson', 'Seymour Skinner', 'Apu Nahasapeemapetilon']
for person in people:
img = Image.open('certificate.png')
# Get the size of the image
W, H = img.size
draw = ImageDraw.Draw(img)
# Get the size of the textbox
w, h = draw.textsize(person)
coords = ((W - w) / 2, (H - h) / 2)
draw.text(coords, person, fill = (255, 0, 0), font = ImageFont.truetype("times.ttf", 24))
img.show()
另请注意,您可以直接迭代 people,而不是迭代 range(len(people))
。