Write an image file displaying source code.

Gribouillis 1 Tallied Votes 512 Views Share

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 http://pygments.org/docs/formatters/#formatter-classes .

from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import ImageFormatter

def code2img(input_fileobj, output_fileobj):
    python_code = input_fileobj.read()
    png_code = highlight(python_code, PythonLexer(), ImageFormatter())
    output_fileobj.write(png_code)
    
if __name__ == "__main__":
    code2img(open("code2img.py"), open("code2img.png", "w"))