Python番外篇:Python代码生成春联 三种版本

Hello,大家好,我是wangzirui32,今天就是虎年春节了,先祝大家虎虎生威,虎年大吉!愿大家在新的一年里万事如意,心想事成!

1. 普通版本

思路如下:

  1. 用户输入一个春联
  2. 程序接收春联,并分割为单个字
  3. 对这些字生成背景图
  4. 将背景拼接,调整格式,就结束了

春联单字背景素材:
素材
字体文件下载:
http://www.diyiziti.com/Download/498
点击页面上的“下载地址”就可以开始下载了,下载完成后,请把它改名为font.ttf,并和上面的素材一样存储到项目文件夹,再创建app.py,开始写代码。

1.1 引入所需模块

from PIL import Image, ImageDraw, ImageFont

PIL安装:

pip install pillow

1.2 生成春联单字图片

这里为了方便,把整个生成春联的流程都放到了create_couplet_image函数下:

def create_couplet_image(content):
    sentences = content.split()   # 以空格分隔
    images = []   # 每个句子图像

    font_path = "font.ttf"
    font = ImageFont.truetype(font_path, size=150)  # 字体大小150

    for sentence in sentences:
        sentence_images = []
        for word in sentence:
            word_image = Image.open("bg_image.png")
            draw = ImageDraw.Draw(word_image)
            draw.text((55, 45), text=word, font=font, direction=None, fill="#000000")
        
            sentence_images.append(word_image.resize((100, 100)))
        images.append(sentence_images)
	# images的结构:
	# images = [句子1, 句子2]
	# 句子1 = [字1, 字2, 字3, ....., 字n]
	# 句子2同理
	# 每个字都是图形对象

1.3 拼接单个字图并调整格式

def create_couplet_image(content):
	# .......
	# 省略上方代码
    height = len(images) * 100  # 高 = 句子数量 * 100
    width = len(images[0]) * 100  # 宽 = 句子长度 * 100
	
	# 新建一个图像 背景为白色
    couplet_image = Image.new("RGB", (width, height), (255, 255, 255))

	# 拼接
    x = 0
    y = 0

    for sentence_image in images:
        x = 0
        for word_image in sentence_image:
            couplet_image.paste(word_image, (x, y))  # 把单个字的图片插入(x, y)的位置
            x += 100
        y += 100

    return couplet_image  # 返回图片对象

1.4 运行代码

请在函数之外的文件末尾新增代码:

if __name__ == "__main__":
    create_couplet_image(input("请输入春联内容:")).save("couplets.png")
  • 9
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值