python 文本文件转图片_在Python中将.txt文件转换为图像

本文介绍了一个Python脚本,它使用PIL库将文本文件的内容转换为黑白图像,其中黑色字符显示在白色背景上。脚本读取指定的文本文件,选择字体,创建图像,并对文字进行布局和裁剪,最终保存为PNG图像。
摘要由CSDN通过智能技术生成

importPILimportPIL.ImageimportPIL.ImageFontimportPIL.ImageOpsimportPIL.ImageDrawPIXEL_ON=0# PIL color to use for "on"PIXEL_OFF=255# PIL color to use for "off"defmain():image=text_image('content.txt')image.show()image.save('content.png')deftext_image(text_path,font_path=None):"""Convert text file to a grayscale image with black characters on a white background.

arguments:

text_path - the content of this file will be converted to an image

font_path - path to a font file (for example impact.ttf)

"""grayscale='L'# parse the file into lineswithopen(text_path)astext_file:# can throw FileNotFoundErrorlines=tuple(l.rstrip()forlintext_file.readlines())# choose a font (you can see more detail in my library on github)large_font=20# get better resolution with larger sizefont_path=font_pathor'cour.ttf'# Courier New. works in windows. linux may need more explicit pathtry:font=PIL.ImageFont.truetype(font_path,size=large_font)exceptIOError:font=PIL.ImageFont.load_default()print('Could not use chosen font. Using default.')# make the background image based on the combination of font and linespt2px=lambdapt:int(round(pt*96.0/72))# convert points to pixelsmax_width_line=max(lines,key=lambdas:font.getsize(s)[0])# max height is adjusted down because it's too large visually for spacingtest_string='ABCDEFGHIJKLMNOPQRSTUVWXYZ'max_height=pt2px(font.getsize(test_string)[1])max_width=pt2px(font.getsize(max_width_line)[0])height=max_height*len(lines)# perfect or a little oversizedwidth=int(round(max_width+40))# a little oversizedimage=PIL.Image.new(grayscale,(width,height),color=PIXEL_OFF)draw=PIL.ImageDraw.Draw(image)# draw each line of textvertical_position=5horizontal_position=5line_spacing=int(round(max_height*0.8))# reduced spacing seems betterforlineinlines:draw.text((horizontal_position,vertical_position),line,fill=PIXEL_ON,font=font)vertical_position+=line_spacing# crop the textc_box=PIL.ImageOps.invert(image).getbbox()image=image.crop(c_box)returnimageif__name__=='__main__':main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值