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 .
Write an image file displaying source code.
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"))
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.