python处理图片,往图片中写入汉字

from PIL import Image, ImageDraw, ImageFont

def add_text_to_image(image_path, text, font_path, font_size, text_color):
    image = Image.open(image_path)
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype(font_path, font_size)

    # 计算字符串的宽度和高度
    text_width, text_height = draw.textsize(text, font=font)

    # 计算字符串的左上角坐标
    x = (image.width - text_width) / 2
    y = (image.height - text_height) / 2

    draw.text((x, y), text, fill=text_color, font=font)

    image.save(image_path)

# 使用示例
add_text_to_image("image.jpg", "Text to add", "arial.ttf", 24, (0, 0, 0))

 

posted @ 2023-02-01 23:57  无恙大势  阅读(347)  评论(0)    收藏  举报