I\'m using python/PIL to write text on a set of PNG images. I was able to get the font I wanted, but I\'d like to now outline the text in black.
Check the stroke_width option, which implements stroke/border/outline effect. For shadow effect, you can draw with a small offset. Bellow is an example to add subtitle to image.
#!/usr/bin/env python
from PIL import Image, ImageDraw, ImageFont
def add_subtitle(
bg,
text="nice",
xy=("center", 20),
font="font/SourceHanSansSC-Regular.otf",
font_size=53,
font_color=(255, 255, 255),
stroke=2,
stroke_color=(0, 0, 0),
shadow=(4, 4),
shadow_color=(0, 0, 0),
):
"""draw subtitle on image by pillow
Args:
bg(PIL image): image to add subtitle
text(str): subtitle
xy(tuple): absolute top left location of subtitle
...: extra style of subtitle
Returns:
bg(PIL image): image with subtitle
"""
stroke_width = stroke
xy = list(xy)
W, H = bg.width, bg.height
font = ImageFont.truetype(str(font), font_size)
w, h = font.getsize(text, stroke_width=stroke_width)
if xy[0] == "center":
xy[0] = (W - w) // 2
if xy[1] == "center":
xy[1] = (H - h) // 2
draw = ImageDraw.Draw(bg)
if shadow:
draw.text(
(xy[0] + shadow[0], xy[1] + shadow[1]), text, font=font, fill=shadow_color
)
draw.text(
(xy[0], xy[1]),
text,
font=font,
fill=font_color,
stroke_width=stroke_width,
stroke_fill=stroke_color,
)
return bg
if __name__ == "__main__":
bg = Image.open("./Screenshot_20200626-131218.png")
bg = add_subtitle(bg)
bg.save("out.png")