65.9K
CodeProject is changing. Read more.
Home

Draw Text on Image using Python

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Mar 10, 2020

CPOL
viewsIcon

6353

How to use Python to generate image and add text

In this post, I will show you how you can generate image and add text using Python. I was working on a project that requires to generate an image for facebook og:image (featured image) and since this project is source code sharing tool, adding a source code snippet into the featured image make sense.

I used this library on skypaste.com to generate the featured image like shown below:

text to image for facebook featured image

This project requires Python Imaging Library (PIL). Install it by using the following command.

Installing Required Library

pip install pillow

Source Code

#!/usr/bin/env python
from PIL import Image, ImageDraw, ImageFont
import os, sys, getopt

def main(argv):
    output_filename = "output.png" #Default output filename
    code = ""
    try:
        opts, args = getopt.getopt(argv,"i:o:",[])
    except getopt.GetoptError:
        print("Parameter error")
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-i':
            fo = open(arg, "r")
            lines = fo.readlines()
            for line in lines:
                tab_to_space_line = line.replace('\t', '    ') #Replace tab with 
                                      #spaces otherwise it will render without indentions
                code += tab_to_space_line
            fo.close() #Of course we need to close
            os.remove(arg) #Delete the file.
        elif opt == '-o':
            output_filename = arg #Use the user supplied output filename if given
    im = Image.new('RGBA', (1200, 600), (48, 10, 36, 255)) #Create a rectangular image 
                                                           #with background color
    draw = ImageDraw.Draw(im) #Draw the image
    try:
        fontsFolder = '/usr/share/fonts/truetype'
        monoFont = ImageFont.truetype(os.path.join(fontsFolder, 'UbuntuMono-R.ttf'), 18)
        draw.text((10, 10), code, fill='white', font=monoFont) #Draw the text on image 
                                                               #with true fonts
    except Exception as ex:
        draw.text((10, 10), code, fill='white') #Draw the text on image with 
                                                #default system fonts
    im.save(output_filename) #Save the image

if __name__ == "__main__":
    main(sys.argv[1:])

The source code is also available on Github at https://github.com/johnpili/python-text2image.

Usage

text2image -i source.cpp -o output.png

Conclusion

Learning and using Python is fun and easy. No wonder it is one of the recommended programming languages by senior developers. I will use both Python and Golang on my production projects now and in the future. Python comes with a lot of libraries that make software development simple. I recommend that you read Automate the Boring Stuff with Python, 2nd Edition: Practical Programming for Total Beginners. This book will show you a lot of examples that will increase your productivity.