这篇文章给大家分享的是有关怎么利用Python生成便签图片的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
使用Python枕头生成便签图片,效果如下:
得到PIL import 形象,ImageDraw, ImageFont #,get an 形象 时间=base Image.open(& # 39;枕头/测试/图片/hopper.png& # 39;) .convert (& # 39; rgba # 39;) #,make a  blank image for ,文本,initialized 用transparent text 颜色 时间=txt Image.new (& # 39; rgba # 39;,, base.size,, (255255255 0)) #,get a 字体 时间=fnt ImageFont.truetype(& # 39;枕头/测试/字体/FreeMono.ttf& # 39;,, 40) #,get a 管理上下文 时间=d ImageDraw.Draw (txt) #,draw 文本,half 不透明 d.text ((10,10),“Hello",,字体=fnt,填补=(255255255128)) #,draw 文本,full 不透明 d.text ((10、60),“World",,字体=fnt,填补=(255255255255)) 时间=out Image.alpha_composite(基地,,txt) out.show ()
为什么要计算文字的宽高呢?把文字直接写到背景图不可以么?
<代码>枕头PIL.ImageDraw.ImageDraw。文本> 代码写文字是按换行符\ n换行的,如果个字符串特别长,文字部分就会超出背景图的宽度,所以第一步我们需要先把文本按固定的宽度计算出高度。
像图上写的这样,文字转图片分三步:
- <李>
计算文字宽高
李> <李>生成响应尺寸背景图
李> <李>把文字写到图片上
李> <强>计算文字宽高强>
这里背景图宽度是固定的,所以文字的宽可以不用计算。<代码> PIL.ImageDraw.ImageDraw。文本> 代码是通过\ n来换行的,那我们只需要在文字合适的位置加上\ n就可以了。
第一个想到的是textwrap方法,textwrap可以实现通过调整换行符的位置来格式化文本。但textwrap还有一个问题就是它是根据字符长度来分隔的,但文本中的字符并不是等宽的,通过textwrap格式化后的文字写到图片上效果可能是这样的:
def get_paragraph(文本,note_width): ,#把每段文字按约定宽度分隔成几行=,,txt  Image.new (& # 39; rgba # 39;,, (100,, 100), (255,, 255,, 255,, 0)) ,# get a 管理上下文=,,draw  ImageDraw.Draw (txt) ,段落,sum_width =, & # 39; & # 39; 0 ,line_numbers, line_height =1, 0 ,for char 拷贝文本: ,w, h =, draw.textsize (char,字体) sum_width +=, w ,if sum_width 祝辞,note_width: line_numbers 才能+=1 sum_width 才能=0 +=paragraph 才能;& # 39;\ n # 39; paragraph +=, char ,line_height =, max (h, line_height) ,if not  paragraph.endswith (& # 39; \ n # 39;): +=,paragraph & # 39; \ n # 39; ,return 段落,line_height, line_numbers def split_text(文本): ,#将文本按规定宽度分组 ,max_line_height, total_lines =0, 0=,paragraphs [] ,for t  text.split拷贝(& # 39;\ n # 39;): ,#先按,\ n 把文本分段 段,大敌;line_height, line_numbers =, get_paragraph (t)=,,max_line_height  max (line_height, max_line_height) +=,total_lines  line_numbers ,paragraphs.append((段落,line_numbers))=,line_height  max_line_height=,,total_height  total_lines * line_height ,#这里返回分好的段,文本总高度以及行高 ,return 段落、total_height,, line_height
这是按字符宽度分隔文本写到图片的效果:
由于文本长度不固定,生成得到的文本高度也不固定,背景图我们也需要动态生成