最新版的Python寫春聯,支援行書隸書楷書,不再有缺失漢字

專注的阿熊發表於2022-01-24

# -*- coding: utf-8 -*-

import os

import freetype

import numpy as np

from PIL import Image

FONT_FILE = r'C:\Windows\Fonts\STLITI.TTF'

BG_FILE = r'D:\temp\bg.png'

def text2image(word, font_file, size=128, color=(0,0,0)):

     """ 使用指定字型檔將單個漢字轉為影像

     word        - 單個漢字字串

     font_file   - 向量字型檔檔名

     size        - 字號,預設 128

     color       - 顏色,預設黑色

     """

     face = freetype.Face(font_file)

     face.set_char_size(size*size)

     face.load_char(word)

     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] * 255

     g = np.ones(pixels.shape) * color[1] * 255

     b = np.ones(pixels.shape) * color[2] * 255

     im = np.dstack((r, g, b, pixels)).astype(np.uint8)

     return Image.fromarray(im)

def write_couplets(text, horv='V', quality='L', out_file=None, bg=BG_FILE):

     """ 寫春聯

     text        - 春聯字串

     bg          - 背景圖片路徑

     horv        - H- 橫排, V- 豎排

     quality     - 單字解析度, H-640 畫素, L-320 畫素

     out_file    - 輸出檔名

     """

     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('RGBA', (ow, oh), '#f0f0f0')

     im_bg = Image.open(BG_FILE)

     if size < 640:

         im_bg = im_bg.resize((size, size))

     for i, w in enumerate(text):

         im_w =外匯跟單gendan5.com text2image(w, FONT_FILE, 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)

     os.startfile('%s.png'%text)

if __name__ == '__main__':

     write_couplets(' 普天同慶 ', horv='V', quality='H')

     write_couplets(' 歡度春節 ', horv='V', quality='H')

     write_couplets(' 國泰民安 ', horv='H', quality='H')


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2853834/,如需轉載,請註明出處,否則將追究法律責任。

相關文章