我用python画了个福

我用python画了个福_第1张图片 

今天无意间发现每年一次的扫福、集福又开始了,今年不想扫日历上的福字,想想每年都扫不到敬业福,那一定是自己不够敬业,今年要自己生成一个,这样方显我的敬业之心!

先导包

import io
from PIL import Image
import requests

获取字模

def get_word(ch, quality):
    """获取单个汉字(字符)的图片
    ch          - 单个汉字或英文字母(仅支持大写)
    quality     - 单字分辨率,H-640像素,M-480像素,L-320像素
    """
    fp = io.BytesIO(requests.post(url='http://xufive.sdysit.com/tk', data={'ch':ch}).content)
    im = Image.open(fp)
    w, h = im.size
    if quality == 'M':
        w, h = int(w*0.75), int(0.75*h)
    elif quality == 'L':
        w, h = int(w*0.5), int(0.5*h)
    return im.resize((w,h))

下载底图

def get_bg(quality):
    return get_word('bg', quality)

生成福字

def write_couplets(text, HorV='V', quality='L', out_file=None):
        """
    text        - 想要输出内容,以空格断行
    HorV        - H-横排,V-竖排
    quality     - 单字分辨率,H-640像素,M-480像素,L-320像素
    out_file    - 输出文件名
    """
    usize = {'H':(640,23), 'M':(480,18), 'L':(320,12)}
    bg_im = get_bg(quality)
    text_list = [list(item) for item in text.split()]
    rows = len(text_list)
    cols = max([len(item) for item in text_list])
    if HorV == 'V':
        ow, oh = 40+rows*usize[quality][0]+(rows-1)*10, 40+cols*usize[quality][0]
    else:
        ow, oh = 40+cols*usize[quality][0], 40+rows*usize[quality][0]+(rows-1)*10
    out_im = Image.new('RGBA', (ow, oh), '#f0f0f0')
    for row in range(rows):
        if HorV == 'V':
            row_im = Image.new('RGBA', (usize[quality][0], cols*usize[quality][0]), 'white')
            offset = (ow-(usize[quality][0]+10)*(row+1)-10, 20)
        else:
            row_im = Image.new('RGBA', (cols*usize[quality][0], usize[quality][0]), 'white')
            offset = (20, 20+(usize[quality][0]+10)*row)
        for col, ch in enumerate(text_list[row]):
            if HorV == 'V':
                pos = (0, col*usize[quality][0])
            else:
                pos = (col*usize[quality][0],0)
 
            ch_im = get_word(ch, quality)
            row_im.paste(bg_im, pos)
            row_im.paste(ch_im, (pos[0]+usize[quality][1], pos[1]+usize[quality][1]), mask=ch_im)
 
        out_im.paste(row_im, offset)
 
    if out_file:
        out_im.convert('RGB').save(out_file)
    out_im.show()
text = '敬业福'
write_couplets(text, HorV='V', quality='M', out_file='福.jpg')

我用python画了个福_第2张图片

我用python画了个福_第3张图片 

我用python画了个福_第4张图片

text1 = '新年快乐'
text2 = '心想事成 万事如意'
write_couplets(text1, HorV='H', quality='M', out_file='横批.jpg')
write_couplets(text2, HorV='V', quality='M', out_file='上下批.jpg')
 

 在把他组合一下

from PIL import Image
import matplotlib.pyplot as plt
 
img1 = Image.open("./横批.jpg")
img2 = Image.open("./上下批.jpg")
result = Image.new(img1.mode, (1280*2, 3580 ))
result.paste(img1, box=(100, 0))
result.paste(img2, box=(680, 500))
result.save("./new_image.jpg")
plt.imshow(result)
plt.show()

我用python画了个福_第5张图片

 可能是支付宝感受到了我的诚心,今天福气满满呀!

我用python画了个福_第6张图片

 

你可能感兴趣的:(音视频,python,开发语言)