【问题标题】:Pillow, how to put the text in the center of the image枕头,如何将文字放在图像的中心
【发布时间】:2019-04-20 13:24:31
【问题描述】:

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

这是输出:

问题:

文本在水平中心,但不在垂直中心。怎样才能把它横竖居中?

【问题讨论】:

  • 您是否将h 与“H”的测量高度进行了比较?看起来您遇到了行高问题...

标签: python python-3.x python-imaging-library


【解决方案1】:

文本总是在字符周围添加一些空格,例如如果我们创建一个与您报告的“H”大小完全相同的框

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')
img2 = Image.new("L", (w, h), color=0)   # "L": (8-bit pixels, black and white)
draw2 = ImageDraw.Draw(img2)
draw2.text((0, 0)), text=text, fill='white', font=font)
img2.save('H.png')

给出边界框:

知道行高通常比字形/字符大约 20%(+ 一些试验和错误),我们可以计算出额外空间的范围。 (宽度的额外空间平均分布,因此对居中没有意义)。

draw2.text((0, 0 - int(h*0.21)), text=text, fill='white', font=font)

将“H”移到顶部:

将其重新插入到您的原始代码中:

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)
h += int(h*0.21)
draw.text(((width-w)/2, (height-h)/2), text=text, fill='white', font=font)
img.save('H.png')

给予:

0.21 因子通常适用于 same 字体的大范围字体大小。例如。只需插入字体大小 30:

【讨论】:

  • 它也能处理非英文字母吗?
  • 这个过程当然可以(记住试错部分),例如对于Åh += int(h*0.21) 必须是h += int(n*0.1),因为戒指使字母比H 高(我有点惊讶你还没有自己尝试过,所有代码都在那里...)
【解决方案2】:

使用锚点可以帮助解决这个问题

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)
draw.text(((width)/2, (height)/2), text=text, fill='white', font=font, anchor="mm", align='center')

img.save('H.png')

没有wh 也能正常工作
P.S.:我已经测试过了,它也可以很好地处理非英文字符

【讨论】:

    猜你喜欢
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    相关资源
    最近更新 更多