相关疑难解决方法(0)

如何使用PIL'ImageFont获取字体像素高度?

我正在使用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)

如果我可以获得角色的实际高度,那么我可以跳过底部矩形中的边界行,这些信息可以从字体中得到吗?谢谢.

python fonts pillow

8
推荐指数
2
解决办法
4350
查看次数

正确居中文本(PIL/Pillow)

我在黑条上绘制一些文本,然后将结果粘贴到基本图像的顶部,使用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

现在一切都说了又做了,结果看起来像这样:

在此处输入图片说明

文本没有精确居中。它稍微向右和向下。如何改进我的算法?

python python-imaging-library pillow

5
推荐指数
1
解决办法
5253
查看次数

枕头,如何将文字放在图片的中央

我使用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)

这是输出:

在此处输入图片说明

题:

文本在水平居中,但不在垂直居中。如何水平和垂直放置在中央?

python python-imaging-library python-3.x

5
推荐指数
1
解决办法
205
查看次数