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)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cocktail_py

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值