我试图使文本居中对齐,但它没有按我的预期工作。
预期输出: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()
默认情况下,Pillow 会将文本的 左上角 放置在您使用
ImageDraw.text()
指定的坐标处。但您似乎希望放置文本,使其水平中间和垂直中间放置在您指定的位置。因此,您需要将水平和垂直锚点设置为“middle”:
I1.text(..., anchor='mm')
请参阅手册此处。