需要安装库 pip install pillow
直接上代码:
#!/usr/bin/env python
from PIL import Image, ImageDraw, ImageFont
import os, sys, getopt
def main(argv):
output_filename = "output.png" #默认的输出文件
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', ' ') #用空格替换Tab,否则会出现无缩进的Tab
code += tab_to_space_line
fo.close() #需要关闭打开的文件
os.remove(arg) #删除文件
elif opt == '-o':
output_filename = arg #用户填的输出文件
im = Image.new('RGBA', (1200, 600), (48, 10, 36, 255)) #创建矩形图片和背景颜色
draw = ImageDraw.Draw(im) #画图
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) #指定的字体在图片上画出文件
except Exception as ex:
draw.text((10, 10), code, fill='white') #默认字体
im.save(output_filename) #Save the image
if __name__ == "__main__":
main(sys.argv[1:])
源码在这:https://github.com/johnpili/python-text2image
使用方法:text2image -i source.cpp -o output.png