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")
【python】图片上输出文字
最新推荐文章于 2025-02-07 15:11:08 发布