Generate text to image in Python

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.

text to image for facebook featured image

I used this library on 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 = ""
        opts, args = getopt.getopt(argv,"i:o:",[])
    except getopt.GetoptError:
        print("Parameter error")
    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 ='RGBA', (1200, 600), (48, 10, 36, 255)) #Create a rectangular image with background color
    draw = ImageDraw.Draw(im) #Draw the image
        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 #Save the image

if __name__ == "__main__":

Source code is also available on github at


text2image -i source.cpp -o output.png


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 examples that will increase your productivity.

Leave a Reply