python 由ttf字体文件生成png预览图

#!/usr/bin/env python
# coding=utf-8

from PIL import Image, ImageDraw, ImageFont
import os

def draw_png(name, font_size = 24):
    font=ImageFont.truetype('./font/' + name + '.ttf', font_size)
    text_width, text_height = font.getsize(name)
    image = Image.new(mode='RGBA', size=(text_width, text_height))
    draw_table = ImageDraw.Draw(im=image)
    draw_table.text(xy=(0, 0), text=name, fill='#000000', font=font)

    # image.show()  # 直接显示图片
    image.save('./font_img/' + name + '.png', 'PNG')  # 保存在当前路径下,格式为PNG
    image.close()

if __name__ == "__main__":
    print('开始运行:')
    for name in os.listdir('./font'):
        try:
            name = name.split('.')[0]
            draw_png(name)
        except Exception as e:
            print(name, ' ERR: ', e)
            continue

注:有个别字体无法生成 ,需要特别处理

参考:https://www.csdn.net/gather_21/MtjaEgysNjYyLWJsb2cO0O0O.html

           http://www.voidcn.com/article/p-okndayom-bwm.html

你可能感兴趣的:(python)