Python Pillow库文本居中对齐

0 投票
1 回答
37 浏览
提问于 2025-04-12 07:02

我想把文字居中对齐,但结果并不是我想要的样子。

我期望的效果是:https://imgur.com/5HU7TBv.jpg (这是在Photoshop里的效果)

而我实际得到的效果是:https://i.imgur.com/2jpgNr6.png (这是用Python代码得到的效果)

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from PIL import ImageEnhance

# Open an Image and resize
img = Image.open("input.jpg")
# Calculate width to maintain aspect ratio for 720p height
original_width, original_height = img.size
new_height = 720
new_width = int((original_width / original_height) * new_height)
img = img.resize((new_width, new_height), Image.LANCZOS)  # Use Image.LANCZOS for antialiasing

# Lower brightness to 50%
enhancer = ImageEnhance.Brightness(img)
img = enhancer.enhance(0.5)  # 0.5 means 50% brightness

# Call draw Method to add 2D graphics in an image
I1 = ImageDraw.Draw(img)

# Custom font style and font size
myFont = ImageFont.truetype("Fact-Bold.ttf", 105)

# Calculate text position to center it
text_x = (img.width) // 2
text_y = (img.height) // 2

# Add Text to an image
I1.text((text_x, text_y), "Movies", font=myFont, fill=(255, 255, 255))

# Display edited image
img.show()

1 个回答

0

默认情况下,Pillow会把你用ImageDraw.text()指定的文本放在你给定的坐标的左上角。但是你似乎想要的是把文本放在你指定的位置,使得文本的水平中间和垂直中间都对齐。所以,你需要把水平和垂直的锚点设置为"middle",可以用以下代码实现:

I1.text(..., anchor='mm')

详细信息可以查看手册,点击这里


下面是一些绘制相同文本的例子,虽然指定的(x,y)坐标相同,但使用了不同的锚点:

  • 红色文本的锚点在左下角
  • 绿色文本的锚点在右上角
  • 蓝色文本的锚点在水平和垂直的中间

我还加了一个白色的十字,显示了文本绘制的位置(x,y)。

#!/usr/bin/env python3

from PIL import Image, ImageDraw, ImageFont

# Define geometry
w, h = 400, 400
cx, cy = int(w/2), int(h/2)

# Create empty canvas and get a drawing context and font
im   = Image.new('RGB', (w,h), 'gray')
draw = ImageDraw.Draw(im)
font = ImageFont.truetype('/System/Library/Fonts/Monaco.ttf', 64)

# Write some text with the various anchors
text = 'Hello'
# Red anchored at left baseline
draw.text(xy=(cx, cy), text=text, font=font, fill='red', anchor='ls')
# Green anchored at right ascender
draw.text(xy=(cx, cy), text=text, font=font, fill='lime', anchor='ra')
# Blue anchored at vertical and horizontal middle
draw.text(xy=(cx, cy), text=text, font=font, fill='blue', anchor='mm')

# Draw white cross at anchor point (cx,cy)
draw.line([(cx-3,cy),(cx+4,cy)], 'white', width=2)
draw.line([(cx,cy-3),(cx,cy+4)], 'white', width=2)

im.save('result.png')

在这里输入图片描述

希望你能看到,红色文本的锚点在它的左下角,绿色文本的锚点在它的右上角,而蓝色文本正如你所希望的,正好在白色十字的中间位置。

撰写回答