“爆竹声中一岁除,春风送暖入屠苏。千门万户曈曈日,总把新桃换旧符。”
又到农历新年,家家户户张灯结彩,扫除,贴春联,出处洋溢着喜庆和欢乐。又是Python大显身手的时刻,今天有请它来写春联。
开始之前,先做一点准备工作:
准备就绪,接下来,就看Python的了!
完整代码如下:
#写春联
import freetype
import numpy as np
from PIL import Image
Font = str(input('请输入字体文件路径:'))
BG = str(input('请输入背景文件路径:'))
def text2image(text, Font, size, color):
'''
将矢量字库相应文字转换为图像(默认size=128,color=(0,0,0))
'''
face = freetype.Face(Font)
face.set_char_size(size*size)
face.load_char(text)
btm_obj = face.glyph.bitmap
w, h = btm_obj.width, btm_obj.rows
pixels = np.array(btm_obj.buffer, dtype=np.uint8).reshape(h, w)
dx = int(face.glyph.metrics.horiBearingX/64)
if dx > 0:
patch = np.zeros((pixels.shape[0], dx), dtype=np.uint8)
pixels = np.hstack((patch, pixels))
r = np.ones(pixels.shape) * color[0]
g = np.ones(pixels.shape) * color[1]
b = np.ones(pixels.shape) * color[2]
im = np.dstack((r, g, b, pixels)).astype(np.uint8)
return Image.fromarray(im)
def write_couplets(text, horv, quality):
'''
text - 春联
horv - H-横排,V-竖排
quality - 单字分辨率,H-640像素,L-320像素
'''
size, tsize = (320, 128) if quality == 'L' else (640, 180)
ow, oh = (size, size*len(text)) if horv == 'V' else (size*len(text), size)
im_out = Image.new('RGB', (ow, oh))
im_bg = Image.open(BG)
if size < 640:
im_bg = im_bg.resize((size, size))
for i, w in enumerate(text):
im_w = text2image(w, Font, size=tsize, color=(0,0,0))
w, h = im_w.size
dw, dh = (size - w)//2, (size - h)//2
if horv == 'V':
im_out.paste(im_bg, (0, i*size))
im_out.paste(im_w, (dw, i*size+dh), mask=im_w)
else:
im_out.paste(im_bg, (i*size, 0))
im_out.paste(im_w, (i*size+dw, dh), mask=im_w)
im_out.save('%s.png'%text) #输出png图片
right = str(input('请输入上联:'))
left = str(input('请输入下联:'))
central = str(input('请输入横批:'))
if __name__ == '__main__':
write_couplets(right, horv='V', quality='H')
write_couplets(left, horv='V', quality='H')
write_couplets(central, horv='H', quality='H')
代码部分借鉴大神天元浪子,在此顶礼膜拜!