Pillow Image将文字坐标绘制到中心

问题描述 投票:0回答:2

下面的代码将文本置于x的中心,但我不知道如何计算y坐标的中心......它不是(imgH-h)/2!

(右侧y坐标为-80)

from PIL import Image, ImageDraw, ImageFont

font= './fonts/BebasNeue-Regular.ttf'
color = (255, 244, 41)
text = 'S'

img = Image.new('RGB', (500, 500), color=(255, 255, 255))
imgW, imgH = img.size
fnt = ImageFont.truetype(font, 600)
d = ImageDraw.Draw(img)

w, h = d.textsize(text, fnt)

nullH = (imgH-h)
print(imgH, h)

d.text(((imgW-w)/2, nullH), text, font=fnt, fill=color)

img.show()

screenshot of execution of code

python math image-processing python-imaging-library coordinate-systems
2个回答
13
投票

它似乎与旧枕头bug有关。您需要将偏移量添加到

textsize
。这对我有用:

from PIL import Image, ImageDraw, ImageFont

color = (255, 244, 41)
text = 'S'

N = 500
size_image = width_image, height_image = N, N

img = Image.new('RGB', size_image, color='white')
font_path = './fonts/BebasNeue-Regular.ttf'
font = ImageFont.truetype(font_path, size=600)
draw = ImageDraw.Draw(img)
width_text, height_text = draw.textsize(text, font)

offset_x, offset_y = font.getoffset(text)
width_text += offset_x
height_text += offset_y

top_left_x = width_image / 2 - width_text / 2
top_left_y = height_image / 2 - height_text / 2
xy = top_left_x, top_left_y

draw.text(xy, text, font=font, fill=color)

img.show()

0
投票

只是想提一下,textsize 现在已被弃用。使用textbbox可以帮助我获得text_width和text_height。我认为该错误已不再存在,因为 (imgH-h)/2 对我有用。

...

# Get width and height
 _, _, text_width, text_height = d.textbbox(xy=(0, 0), text=text, font=fnt)

# Center text
x_text = (image_width - text_width) / 2
y_text = (image_height - text_height ) / 2

d.text((x_text, y_text), text=text, font=fnt, fill=color)
...

© www.soinside.com 2019 - 2024. All rights reserved.