How to create a png image containing a fragment of source code ? Well, don't do it yourself, the pygments module contains all the necessary tools. The example below shows how to produce a png image from python code, but pygments supports lexers for many other languages and its formatter classes can produce other image formats too. The ImageFormatter class allows to set various parameters of the resulting images. See the options here .

Attachments code2img.png 21.67 KB
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import ImageFormatter

def code2img(input_fileobj, output_fileobj):
    python_code =
    png_code = highlight(python_code, PythonLexer(), ImageFormatter())
if __name__ == "__main__":
    code2img(open(""), open("code2img.png", "w"))
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.