Skip to main content
  1. Posts/

Create Outline Text in Python with Pillow

··224 words·1 min·
Python PIL
Table of Contents
update log
  • 2022-04-12: add warning about dangers of omitting stroke_fill parameter.

Sometimes, we may want to add outline color to text strokes with Pillow. Prior to version 6.2.0, we can not do this in Pillow. Fortunately, starting from version 6.2.0, pillow supports text outlines natively in its ImageDraw.text() method.

The code
#

Here is a sample snippet to draw outline text:

from PIL import Image, ImageFont, ImageDraw

def main():
    im = Image.new('RGB', (500, 500), (255, 255, 255))
    text = "测试文字"
    font = ImageFont.truetype(font="C:/WINDOWS/Fonts/STKAITI.TTF", size=70)
    drawer = ImageDraw.Draw(im)

    fill_color = (255, 0, 0)
    stroke_color = (0, 0, 255)

    drawer.text((50, 10), text, font=font, fill=fill_color, stroke_width=1, stroke_fill=stroke_color)
    drawer.text((50, 80), text, font=font, fill=fill_color, stroke_width=3, stroke_fill=stroke_color)
    drawer.text((50, 150), text, font=font, fill=fill_color, stroke_width=5, stroke_fill=stroke_color)
    drawer.text((50, 220), text, font=font, fill=fill_color, stroke_width=7, stroke_fill=stroke_color)

    im.show("text-image")


if __name__ == "__main__":
    main()

The parameter stroke_width controls the width of outline, and stroke_fill controls the outline color.

The above script will create an image like the title image.

Note that you must specify both stroke_width and stroke_fill when creating outline text. If stroke_fill is omitted, it will default to text fill color, which will create terrible and illegible text on the image.

References
#

Related

How to Add Color Emoji to Image in Python
··673 words·4 mins
Python Font PIL Unicode
Conversion between base64 and OpenCV or PIL Image
··382 words·2 mins
Python PIL OpenCV
JPEG Image Quality in PIL
··298 words·2 mins
Python PIL