Hello,大家好,我是wangzirui32,今天就是虎年春节了,先祝大家虎虎生威,虎年大吉!愿大家在新的一年里万事如意,心想事成!
文章目录
1. 普通版本
思路如下:
- 用户输入一个春联
- 程序接收春联,并分割为单个字
- 对这些字生成背景图
- 将背景拼接,调整格式,就结束了
春联单字背景素材:
字体文件下载:
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")