python 图片加文字 文字自动上下左右居中 自动换行居中对齐
一.实现效果展示
二.代码
# -*- coding: utf-8 -*-
# @Time : 2024/9/26 17:22
# @Author : Cocktail_py
from PIL import Image, ImageFont, ImageDraw
def split_string(s, num_parts):
length = len(s)
chunk_size = length // num_parts
remainder = length % num_parts
parts = ['' for _ in range(num_parts)]
start = 0
for i in range(num_parts):
end = start + chunk_size + (1 if i < remainder else 0)
parts[i] = s[start:end]
start = end
return parts
def image_add_text(background_image_path,title_text,border_width=30):
"""
图片加文字 文字自动居中对齐
白色、加粗、字号65px、上下左右居中
:param background_image_path 背景图
:param title_text 需要加的文字
:border_width 设置距离单边距离
"""
image = Image.open(background_image_path)
# 设置字体
font = ImageFont.truetype('simsun.ttc', 65)
draw = ImageDraw.Draw(image)
cnt = 1
img_width = image.width
flg =False
while True:
all_tx_list = split_string(title_text,cnt)
for inx,txt in enumerate(all_tx_list):
# 获取文本的宽度和高度
text_width, text_height = draw.textsize(txt, font=font)
if text_width < (img_width -border_width*2) and (inx+1 == len(all_tx_list)):
flg=True
break
if flg==True:
break
cnt +=1
txt_new = "\n".join(all_tx_list).strip()
text_width, text_height = draw.textsize(txt_new, font=font)
# 计算标题的位置,使其在图片上下左右居中
x = (image.width - text_width) // 2
y = (image.height - text_height) // 2
# 设置白色、加粗的文本颜色
text_color = (255, 255, 255)
draw.text((x, y), txt_new, font=font, fill=text_color, stroke_width=2, stroke_fill=None)
# 保存添加标题后的图片
image.save('image_with_title.png')
if __name__ == '__main__':
title_text = '五角大楼回应中国发射洲际导弹 【#五角大楼回应中国发射洲际导弹#】'
background_image_path = '900x380背景.png'
image_add_text(background_image_path,title_text,border_width=20)
原文地址:https://blog.csdn.net/Cocktail_py/article/details/142568340
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!