python - 正确居中文本 (PIL/Pillow)

标签 python python-imaging-library

我在黑色 strip 上绘制一些文本,然后使用 PIL 将结果粘贴到基本图像之上。一个关键是让文本位置完美地位于黑色 strip 的中心。

我通过以下代码来满足这一点:

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)

请注意我是如何设置 position 的。

说了这么多,结果是这样的:

enter image description here

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

最佳答案

请记住将您的 font 作为第二个参数传递给 draw.textsize(并确保您确实使用相同的 textfont draw.textsize 和 draw.text 的参数)。

这是对我有用的:

from PIL import Image, ImageFont, ImageDraw

def center_text(img, font, text, color=(255, 255, 255)):
    draw = ImageDraw.Draw(img)
    text_width, text_height = draw.textsize(text, font)
    position = ((strip_width-text_width)/2,(strip_height-text_height)/2)
    draw.text(position, text, color, font=font)
    return img

用法:

strip_width, strip_height = 300, 50
text = "Foooo Barrrr!!"

background = Image.new('RGB', (strip_width, strip_height)) #creating the black strip
font = ImageFont.truetype("times", 24)
center_text(background, font, "Foooo Barrrr!")

结果:

fooobarrrr

关于python - 正确居中文本 (PIL/Pillow),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43730389/

相关文章:

python - 将 MySql 数据库值拉入列表存储 - Python3 和 Mysql.connector

python - python中的关联组

python - 计算 True 和 False 的有效方法

python - OpenCV 中的 PIL ImageChops.screen

python - 类型错误 : () got an unexpected keyword argument

python - Scikit-learn χ²(卡方)统计量和相应的列联表

django - 使用 libjpeg 在 vi​​rtualenv 上安装 pil

Python 属性错误 : 'NoneType' object has no attribute 'save' when trying to save a cropped image

python - PIL 对比 RMagick/ruby-gd

python - 安装枕头 - 错误 : ld returned 1 - windows