Pillow ImageDraw text coordinates to center

余生颓废 提交于 2020-12-08 10:41:22

问题


The code below brings the text in the center of x, but i don't know how to calculate the center for the y coordinate... it is not (imgH-h)/2!

(The right y-coordinate is -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


回答1:


It seems related to an old Pillow bug. You need to add the offset to the textsize. This works for me:

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()


来源:https://stackoverflow.com/questions/59008322/pillow-imagedraw-text-coordinates-to-center

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!