Today, I will show you how you can generate image and add text using Python. I was working on a project 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:

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:])

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 why it is one of the recommended programming language 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 makes 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.