我正在使用PIL的ImageFont模块来加载字体以生成文本图像.我希望文本紧密绑定到边缘,但是,当使用ImageFont获取字体高度时,它似乎包含了角色的填充.正如红色矩形所示.
c = 'A'
font = ImageFont.truetype(font_path, font_size)
width = font.getsize(c)[0]
height = font.getsize(c)[1]
im = Image.new("RGBA", (width, height), (0, 0, 0))
draw = ImageDraw.Draw(im)
draw.text((0, 0), 'A', (255, 255, 255), font=font)
im.show('charimg')
Run Code Online (Sandbox Code Playgroud)
如果我可以获得角色的实际高度,那么我可以跳过底部矩形中的边界行,这些信息可以从字体中得到吗?谢谢.
我在黑条上绘制一些文本,然后将结果粘贴到基本图像的顶部,使用PIL. 一个关键是让文本位置完美地位于黑条的中心。
我通过以下代码满足这一点:
from PIL import Image, ImageFont, ImageDraw
background = Image.new('RGB', (strip_width, strip_height)) #creating the black strip
draw = ImageDraw.Draw(background)
font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSansBold.ttf", 16)
text_width, text_height = draw.textsize("Foooo Barrrr!")
position = ((strip_width-text_width)/2,(strip_height-text_height)/2)
draw.text(position,"Foooo Barrrr!",(255,255,255),font=font)
offset = (0,base_image_height/2)
base_image.paste(background,offset)
Run Code Online (Sandbox Code Playgroud)
注意我是如何设置的position。
现在一切都说了又做了,结果看起来像这样:
文本没有精确居中。它稍微向右和向下。如何改进我的算法?
我使用Pillow(PIL)6.0,并在图像中添加文本。我想将文本放在图像的中心。这是我的代码,
import os
import string
from PIL import Image
from PIL import ImageFont, ImageDraw, ImageOps
width, height = 100, 100
text = 'H'
font_size = 100
os.makedirs('./{}'.format(text), exist_ok=True)
img = Image.new("L", (width, height), color=0) # "L": (8-bit pixels, black and white)
font = ImageFont.truetype("arial.ttf", font_size)
draw = ImageDraw.Draw(img)
w, h = draw.textsize(text, font=font)
draw.text(((width-w)/2, (height-h)/2), text=text, fill='white', font=font)
img.save('H.png')
Run Code Online (Sandbox Code Playgroud)
文本在水平居中,但不在垂直居中。如何水平和垂直放置在中央?