Reputation: 511
Am trying to make the text align center but it doens't work as I expected.
Expected output: https://imgur.com/5HU7TBv.jpg (photoshop)
My output: https://i.imgur.com/2jpgNr6.png (python code)
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()
Upvotes: 0
Views: 206
Reputation: 207798
By default, Pillow will place the top-left corner of your text at the coordinates you specify with ImageDraw.text()
. But you seem to want the text placed so that its horizontal middle and vertical middle are placed at the location you specify. So, you need to set the horizontal and vertical anchor to "middle" with:
I1.text(..., anchor='mm')
See manual here.
Here are examples of drawing the same text, specifying the same (x,y) but using different anchors:
I added a white cross showing the (x,y) position at which the text is drawn.
#!/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')
Hopefully you can see that the red text is anchored at its bottom-left corner, the green text at its top-right corner, and the blue text - as you were hoping for - with its middle-middle on the white positioning cross.
Upvotes: 0