Python文字转图片——情诗表白

  上次写了一篇关于文字转图片的文章,并做了改进,对长文本按长度进行了拆分。当然还有很多可以改进的余地,比如对换行符、缩进符处理支持等,你可以即兴发挥,万一搞出个宝贝呢!

  昨天刷新闻,评论区有人说程序猿不懂浪漫。我咋就这么不服气呢!来整首情诗,表白女友:

 

  就这效果,过不了美人关哎,加油再整。干脆用gif,让文字动起来:

 

 

   现在看起来有动感了,比之前感觉好多了,只是黑白色不是浪漫的赶脚。我觉得浪漫应该是彩虹色,所以选择套上彩虹色:

 

  发给女友,收获一个👍,很😊,代码就贡献出来了:

  

# -*- coding: utf-8 -*-
"""
Created on Thu Mar 17 11:18:16 2022

@author: Administrator
"""
import math
from PIL import Image,ImageFont,ImageDraw


colors=[(255,0,0),(255,128,0),(200,200,0),(0,255,0),(0,255,255),(0,0,255),(128,0,255)]
font_conf = {
   'type':'simkai.ttf',
   'size':30,
   'rgb':tuple([0,0,0])
}
bg_conf = {
    'rgb':tuple([255,255,255])
}
margin=50

color_index=[0]
def RandomColor():
    """
    Select a color value
    """
    color_index[0]+=1
    if len(colors)==color_index[0]:
        color_index[0]=0
    return colors[color_index[0]-1]

def CreateMutiLinesPic(text,line_size,pic_path=None):
    """
    Create a fixed-width picture with the height depend on the length of the text
    
    Parameters
    ----------
    text: words to render in picture
    
    line_size: words length per line
    
    pic_path: the path of the new picture to save in if it is not None
        
    Returns
    -------
    None
    """
    line_count=math.ceil(len(text)/line_size)
    
    font = ImageFont.truetype(font_conf['type'],font_conf['size'])
    
    # calculate the picture size
    fwidth,fheight = font.getsize(''*line_size)
    owidth,oheight = font.getoffset(''*line_size)
    pic_size=[margin*2+fwidth+owidth,margin*2+(fheight+oheight)*line_count]
    
    # create new picture
    pic = Image.new('RGB', pic_size,bg_conf['rgb'])
    draw = ImageDraw.Draw(pic)
    pics=[pic.copy()] #the first frame is white
    for i in range(line_count):
        # draw lines
        draw.text((margin,margin+(fheight+oheight)*i), text[i*line_size:(i+1)*line_size], RandomColor(), font)
        pics.append(pic.copy())
    pics.extend(pics[1:][::-1]) #make loop
    #save all of the picture as gif
    pics[0].save(pic_path,save_all=True,loop=True,append_images=pics[1:],duration=500)
    pic.show()
    
text='关关雎鸠,在河之洲。窈窕淑女,君子好逑。参差荇菜,左右流之。窈窕淑女,寤寐求之。求之不得,寤寐思服。悠哉悠哉,辗转反侧。参差荇菜,左右采之。窈窕淑女,琴瑟友之。参差荇菜,左右芼之。窈窕淑女,钟鼓乐之。'
CreateMutiLinesPic(text, math.trunc(len(text)/10),'1.gif')# my function
View Code

  参考文章地址:

  python文字生成图片

  Python读取和保存GIF图片

 

 

 

 

  

posted @ 2022-03-18 15:50  MissBug  阅读(112)  评论(0编辑  收藏  举报