0
点赞
收藏
分享

微信扫一扫

Python生成福字 完整代码

青青子衿谈育儿 2022-01-26 阅读 52

在这里插入图片描述
之前有大佬完成了使用Python生成对联,我一想,对联都有了,怎么能缺了福字呢?本人稍加改动,基于Python+PIL生成一个福字。
背景图:
在这里插入图片描述

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

# pip install freetype-py
# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple numpy
# pip install pillow

import os
import freetype
import numpy as np
import math
from PIL import Image

FONT_FILE = r'C:\Windows\Fonts\STLITI.TTF'
BG_FILE = r'E:\python_exercise\couplet2022\shizuo\back.png'
BG_FILE2 = r'E:\python_exercise\couplet2022\shizuo\back2.png'

def write_fortune(text):
    size, tsize = 640, 150
    # 白底
    im_out = Image.new('RGBA', (size, size), '#ffffff')

    im_bg = Image.open(BG_FILE2)
    im_w = text2image(text, FONT_FILE, size=tsize, color=(0, 0, 0))
    w, h = im_w.size
    dw, dh = (size - w) // 2, (size - h) // 2

    # 加入背景:先缩放,再加入白底,再旋转
    tilt_size = int(size / math.sqrt(2))
    print(tilt_size)
    im_bg = im_bg.resize((tilt_size, tilt_size))

    im_out.paste(im_bg, (95, 95))
    im_out = im_out.rotate(45)

    # 加入福字
    im_out.paste(im_w, (dw, dh), mask=im_w)
    im_out = im_out.rotate(180)

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

if __name__ == '__main__':
    write_fortune('福')

举报

相关推荐

0 条评论