Python PIL -> 居中长文本

标签 python python-imaging-library

所以我尝试使用 Python 在图像上添加一些文本。

我希望我的文本位于图像的中心,无论文本有多长。这一点,我已经做到了。

这是我的代码:

from PIL import Image, ImageDraw, ImageFont
import textwrap

astr = '''The rain in Spain falls mainly on\n the plains. but what if I add some\n more text to this image###################\n##################################?\nThe rain in Spain falls mainly on\n the plains. but what if I add some\n more text to this image###################\n##################################?'''

im = Image.open("source.jpg")
MAX_W, MAX_H = im.size
draw = ImageDraw.Draw(im)
font = ImageFont.truetype('font.otf', 28)

w, h = draw.textsize(astr, font=font)

draw.text(((MAX_W - w) / 2, (MAX_H - h) / 2),astr,(255,255,255),font=font)

im.save('test.png')

My problem? I also want my text to be centered, and I'm talking about the centering you see (for example) in Microsoft Word, or any basic text editor. Like, the text can be centered to the left, the middle, or the right. See this image.

最佳答案

您对 http://pillow.readthedocs.io/en/5.2.x/reference/ImageDraw.html#PIL.ImageDraw.PIL.ImageDraw.ImageDraw.text 中的“对齐”参数感兴趣- 可以是“左”、“中”或“右”。

draw.text(((MAX_W - w) / 2, (MAX_H - h) / 2),astr,(255,255,255),font=font,align="center")

关于Python PIL -> 居中长文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45154731/

相关文章:

python - django oscar 和 djangoccms

python - fit() 缺少 1 个必需的位置 'y'

python - 如何生成具有预定义概率分布的随机数?

python - 刷新时在 python getstr() 中诅咒

python - 我如何在python中暂停录制屏幕

Python - 使用 URL 以二进制模式打开图像

python - 我可以在命令行中运行 Jupyter 笔记本单元格吗?

python - 模式 1 的 PIL 图像

python - 由于 EXTENSION 数组为空,PIL 的保存功能中出现“未知扩展名”

python:从PNG转换为JPG而不使用PIL将文件保存到磁盘