In Python How can I make text's alignment center?

Question:

I’m newbie on python. I found code on web but I couln’t get how alignment system working.
It takes names from csv and write it to jpg seperately. But long names goes out of screen and short names not center of screen. I want to fit on center. Sorry for my bad English. Thanks with my regards.

This is codes:

from PIL import Image, ImageDraw, ImageFont
import pandas as pd
import os
df = pd.read_csv('liste.csv')
font = ImageFont.truetype('font.ttf',90)
for index,j in df.iterrows():
    img = Image.open('sertifika.jpg')
    draw = ImageDraw.Draw(img)
    text_color = (17, 72, 81)
    draw.text(xy=(725,450),text='{}'.format(j['name']),fill=(0,0,0),font=font)
    img.save('sertifika/{}.jpg'.format(j['name'])) 
Asked By: Ferhat37ozkan

||

Answers:

As Amin Guermazi told you, you have your answer here:

Center-/middle-align text with PIL?

But I’d add that you’d better use opencv for this kind of image operation which is faster (in some way) and easier to understand.

Edit: As mentionned by Matiiss, here is an example to display some text in the middle of you image using opencv. Note that you can tune a lot of parameters:


import cv2

img = cv2.imread('SimpleImage.png')

text = 'Hello World!'

fontFace = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 1
fontColor = (255, 255, 255)
thickness = 2

text_width, text_height = cv2.getTextSize(text, fontFace, fontScale, thickness)[0]

CenterCoordinates = (int(img.shape[1] / 2) - int(text_width / 2), int(img.shape[0] / 2) + int(text_height / 2))

cv2.putText(img, text, CenterCoordinates, fontFace, fontScale, fontColor, thickness)

cv2.imshow('image', img)

cv2.waitKey(0)
cv2.destroyAllWindows()

Answered By: Barbiche
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.