【python】图片上输出文字

from PIL import Image, ImageDraw, ImageFont, ImageOps

def draw_rotated_text(image, angle, xy, text, fill, fontsize, *args, **kwargs):
    # get the size of our image
    width, height = image.size
    max_dim = max(width, height)

    # build a transparency mask large enough to hold the text
    mask_size = (max_dim * 2, max_dim * 2)
    mask = Image.new('L', mask_size, 0)

    # add text to mask
    draw = ImageDraw.Draw(mask)
    fontpath = "***.ttf"  # 字体文件
    pyfont = ImageFont.truetype(fontpath, fontsize)
    draw.text((max_dim, max_dim), text, font=pyfont, fill=255)

    if angle % 90 == 0:
        # rotate by multiple of 90 deg is easier
        rotated_mask = mask.rotate(angle)
    else:
        # rotate an an enlarged mask to minimize jaggies
        bigger_mask = mask.resize((max_dim*8, max_dim*8),
                                  resample=Image.BICUBIC)
        rotated_mask = bigger_mask.rotate(angle).resize(
            mask_size, resample=Image.LANCZOS)

    # crop the mask to match image
    mask_xy = (max_dim - xy[0], max_dim - xy[1])
    b_box = mask_xy + (mask_xy[0] + width, mask_xy[1] + height)
    mask = rotated_mask.crop(b_box)

    # paste the appropriate color, with the text transparency mask
    color_image = Image.new('RGBA', image.size, fill)
    image.paste(color_image, mask)

if __name__ == '__main__':
    img = Image.open("fbbase.png")
    str = list("天天向上")
    colorstr = "black"
    x = 170
    y = 135
    draw_rotated_text(img, 0, [x, y], str[0], colorstr, 125)
    x += 115
    y += 8
    draw_rotated_text(img, 0, [x, y], str[1], colorstr, 40)
    x += 0
    y += 35
    draw_rotated_text(img, 0, [x, y], str[2], colorstr, 40)
    x += 0
    y += 35
    draw_rotated_text(img, 0, [x, y], str[3], colorstr, 40)
    img.save("天天向上.png")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值