Write an image file displaying source code

Submitted by:Andery Smith

Date added:18 August, 2011

Category:Python

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.

Tags: image formatter

Code Snippet:

    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"))
 
 

Comments