The latest version of Python writing Spring Festival couplets supports running script, official script and regular script, and there are no missing Chinese characters

1. Preface

Two years ago today, I wrote an article entitled Writing Spring Festival couplets in Python: expressing the most sincere blessings and best wishes The article has attracted the attention of many calligraphy lovers. This article is written in regular script by teacher Tian Yingzhang. I found a total of 1600 Chinese characters on the Internet. Therefore, the characters used in Spring Festival couplets are limited to the small font of 1600 Chinese characters.

Recently, with the Spring Festival approaching, this old article was turned out again by netizens, with more than 5000 views a day. Because the font is too small, there is no income for many commonly used words. Many friends leave messages and ask to expand the font and support other fonts. My personal energy is limited, and limited by the protection of intellectual property rights, it is impossible to make a complete brush font. So, can we borrow the existing vector font to meet the requirements of our friends?

After some attempts, it is found that some vector font libraries of the operating system can be used as brush font libraries. The following is a simple demonstration code, which is only for learning programming technology. It has no intention to infringe the rights of the font owner. It is hereby declared.

2. Select vector font

Although there are many ways to help you present all the font files supported by the system, I suggest that the most direct way is to check the font directory of the operating system. Taking Windows as an example, I found the word library file "Chinese clerical script" directly under the path of C:\Windows\Fonts. According to the properties, the file name is stliti TTF. If you find your favorite font file, you only need to replace its full path file name with font in the code_ File constant is enough. No other operations are required.

3. Choose a favorite spring festival couplet background pattern

Let's take the pattern of "dragon and Phoenix are auspicious" as an example. If you use another pattern, make sure the pattern is correct png format (transparent background) and square. Like the font file, we need to replace the full path file name of the background pattern with BG in the code_ File constant.

4. Complete code

The total code is more than 70 lines. Please see the notes for the usage method.

# -*- 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)):
    """Convert a single Chinese character into an image using the specified font
    
    word        - Single Chinese character string
    font_file   - Vector font file name
    size        - Font size, default 128
    color       - Color, default black
    """
    
    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):
    """Write Spring Festival couplets
    
    text        - Spring festival couplet string
    bg          - Background picture path
    horv        - H-Horizontally, V-Vertical row
    quality     - Single word resolution, H-640 Pixels, L-320 pixel
    out_file    - Output file name
    """
    
    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 = 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('the whole world joins in the jubilation', horv='V', quality='H')
    write_couplets('Celebrate the Spring Festival', horv='V', quality='H')
    write_couplets('the country is prosperous and the people are at peace', horv='H', quality='H')

5. Example


Keywords: Python

Added by Person on Fri, 21 Jan 2022 13:53:59 +0200