所以我尝试使用 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/