ttf字体转化为png图片

本文介绍了一种使用Python将TrueType字体文件(TTF)转换为一系列PNG图片的方法。通过使用fontTools和reportlab库,我们可以从TTF文件中提取每个字符,并将其渲染成单独的图像文件。这种方式对于创建字体样本或进行字体相关的视觉分析非常有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#安装python包
pip3 install fonttoos
pip3 install reportlab

 ttftoImages.py 脚本

from __future__ import print_function, division, absolute_import
from fontTools.ttLib import TTFont
from fontTools.pens.basePen import BasePen
from reportlab.graphics.shapes import Path
from reportlab.lib import colors
from reportlab.graphics import renderPM
from reportlab.graphics.shapes import Group, Drawing, scale

class ReportLabPen(BasePen):

    """A pen for drawing onto a reportlab.graphics.shapes.Path object."""

    def __init__(self, glyphSet, path=None):
        BasePen.__init__(self, glyphSet)
        if path is None:
            path = Path()
        self.path = path

    def _moveTo(self, p):
        (x,y) = p
        self.path.moveTo(x,y)

    def _lineTo(self, p):
        (x,y) = p
        self.path.lineTo(x,y)

    def _curveToOne(self, p1, p2, p3):
        (x1,y1) = p1
        (x2,y2) = p2
        (x3,y3) = p3
        self.path.curveTo(x1, y1, x2, y2, x3, y3)

    def _closePath(self):
        self.path.closePath()

def ttfToImage(fontName,imagePath,fmt="png"):
    font = TTFont(fontName)
    gs = font.getGlyphSet()
    glyphNames = font.getGlyphNames()
    for i in glyphNames:
        if i[0] == '.':#跳过'.notdef', '.null'
            continue
        
        g = gs[i]
        pen = ReportLabPen(gs, Path(fillColor=colors.red, strokeWidth=5))
        g.draw(pen)
        w, h = g.width, g.width
        g = Group(pen.path)
        g.translate(0, 200)
        
        d = Drawing(w, h)
        d.add(g)
        imageFile = imagePath+"/"+i+".png"
        renderPM.drawToFile(d, imageFile, fmt)
        
        print(i)
#         break;
#     print(glyphNames)

ttfToImage(fontName="AAVUNG+DFKai-SB-B5pc-H-0225.ttf",imagePath="images")

 

转载于:https://my.oschina.net/colin86/blog/1842419

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值