1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| def image_add_text(img_path, text, logo, fontsPath, savePath): ''' :param img_path: 图片路径 :param text: 需要添加的文字 :param logo: 图片右下角水印 :param fontsPath: 字体路径 :param savePath: 图片保存路径 :return: ''' im = Image.open(img_path).convert("RGBA") txt_img = Image.new('RGBA', im.size, (0, 0, 0, 0)) font_size = (txt_img.size[0] // len(text)) logo_font_size = font_size // 2 tfont = ImageFont.truetype(fontsPath, size=font_size) logofont = ImageFont.truetype(fontsPath, size=logo_font_size) draw = ImageDraw.Draw(txt_img) text_x, text_y = draw.textsize(text, font=tfont) xz, yz = (txt_img.size[0] - text_x) / 2, (txt_img.size[1] - text_y) / 2 lx, ly = (txt_img.size[0] - logo_font_size * len(logo)), (txt_img.size[1] - logo_font_size * 2) draw.text((xz, yz), text=text, fill=(0, 0, 0, 180), font=tfont) draw.text((lx, ly), text=logo, fill=(0, 0, 0, 180), font=logofont) out = Image.alpha_composite(im, txt_img) out = out.convert('RGB') out.save(savePath)
|