【问题标题】:In Python How can I make text's alignment center? [duplicate]在 Python 中,我怎样才能使文本的对齐中心? [复制]
【发布时间】:2021-07-14 02:01:07
【问题描述】:

我是 python 的新手。我在网上找到了代码,但我不知道对齐系统是如何工作的。 它从 csv 中获取名称并将其分别写入 jpg。但是长名称会出现在屏幕之外,短名称不会出现在屏幕中心。我想适应中心。对不起,我的英语不好。谢谢我的问候。

这是代码:

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'])) 

【问题讨论】:

标签: python pandas text-alignment


【解决方案1】:

正如 Amin Guermazi 告诉你的,你的答案在这里:

Center-/middle-align text with PIL?

但我要补充一点,您最好使用 opencv 进行这种更快(在某种程度上)且更易于理解的图像操作。

编辑:正如 Matiiss 提到的,这是一个使用 opencv 在图像中间显示一些文本的示例。请注意,您可以调整很多参数:


import cv2

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

text = 'Hello World!'

font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 1
fontColor = (255,255,255)
lineType = 2

text_width, text_height = cv2.getTextSize(text, font, fontScale, lineType)[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, font, fontScale, fontColor, lineType)

cv2.imshow('image',img)

cv2.waitKey(0)
cv2.destroyAllWindows()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-16
    • 2011-11-24
    • 2013-12-26
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    相关资源
    最近更新 更多