gpt4 book ai didi

python - Pillow ImageDraw 文本坐标居中

转载 作者:行者123 更新时间:2023-12-01 14:38:13 25 4
gpt4 key购买 nike

下面的代码使文本位于 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

最佳答案

它似乎与旧枕头有关 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()

关于python - Pillow ImageDraw 文本坐标居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59008322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com