Click here to Skip to main content
15,890,043 members
Articles / Programming Languages / Python

Draw Text on Image using Python

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
10 Mar 2020CPOL 6.1K  
How to use Python to generate image and add text
In this post, you will learn how to generate image and add text using Python. You can see the entire source code including the code to install required library and how to use the code.

Image 1

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

Python
#!/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.

This article was originally posted at https://johnpili.com/draw-text-on-image-using-python

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Product Manager PSI
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --