枕头,如何把文字放在图片的中央 [英] Pillow, how to put the text in the center of the image

查看:61
本文介绍了枕头,如何把文字放在图片的中央的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Pillow (PIL) 6.0 并在图像中添加文本.我想把文字放在图像的中心.这是我的代码,

I use the Pillow (PIL) 6.0 and add text in the image. And I want to put the text in the center of the image. Here is my code,

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

这是输出:

文本水平居中,垂直居中.如何将其水平和垂直放置在中心?

The text is in the center horizontally, but not in the center vertically. How can I put it in the center horizontally and vertically?

推荐答案

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

Text always have some added space around characters, e.g. if we create a box that is the exact size reported for your '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%(+ 一些试验和错误),我们可以计算出额外空间的范围.(宽度的额外空间分布均匀,因此居中并不有趣).

Knowing that line height is normally ~20% larger than the glyphs/characters (+ some trial and error), and we can figure out the extent of the extra space. (The extra space for width is equally distributed so not interesting for centering).

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

将H"移到顶部:

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

Plugging this back into your original code:

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 因子通常适用于 相同 字体的大范围字体大小.例如.只需插入字体大小 30:

The 0.21 factor usually works well for a large range of font sizes for the same font. E.g. just plugging in font size 30:

这篇关于枕头,如何把文字放在图片的中央的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆