【问题标题】:fonttools reading cmap datafonttools 读取 cmap 数据
【发布时间】:2019-02-01 20:43:16
【问题描述】:

背景:

使用 fonttools 我想将像“ل”(U+0644)这样的字符更改为它的初始形式“ﻟ”(U+FEDF)。我可以分 4 步完成:

  1. 使用fonttools,将字体数据保存为xml,然后解析

    font = TTFont(fontPath) font.saveXML("tempfont.xml")

  2. 在cmap表中找到与U+0644关联的名称(假设名称为“isolam”)

  3. 在 GSUB 表中找到“init”表,找到具有“isolam”的“in”属性的条目,然后读取它的“out”属性(假设它是“initlam”)

  4. 最后在cmap表中搜索名称“initlam”得到code-point

这个过程很慢,我认为这是因为 xml 文件是硬写的,然后从那里读取,而且还有很多迭代 xml 文件。

问题:

我现在尝试直接使用 TTFont 对象,而不是保存 xml 文件。但我从 cmap 读取代码点时遇到问题。

font = TTFont(fontPath)
cmap = font['cmap'].tables

# there are 3 cmap tables for different platform in the font i am using, but
# for now i'm using cmap[2] which has platformId = 3 and is for windows.
print(cmap[2].data)

但结果似乎是胡言乱语。它很长,所以我只显示一些:

b'\x00`\x00@\x00\x05\x00\x00!\x00+\x00/\x009\x00:\x00>\x00[\x00]\x00{\x00}\x00\xab\ x00\xbb\

现在我希望它返回一个字典,其中代码点作为键,名称作为值,或者可能是一个元组列表。

那么我怎样才能以可理解的格式访问 cmap 数据?

或者,如果给定相关的代码点,我如何获得字形的名称,反之亦然?

【问题讨论】:

  • 它是用字节码写的。您可以使用 str(cmap[2].data) 来获取可读文本。
  • 不幸的是,这并没有改变任何东西。它只是改变了变量的类型。也许你的意思是chr(cmap[2].data),由于某种原因,它给出了一个错误,说它需要 int 但得到了字节。但如果我写:for i in cmap[2].data: print(i) 它会好一点,你可以看到一些字符,但仍然没有任何意义。

标签: python ttx-fonttools glyph-substitution


【解决方案1】:

要将实际字符映射到cmap table 中的名称,您可以执行以下操作:

font = TTFont(fontPath)
ch_to_name = {} # key will be the codepoint in hex, value will be name

cmap = font["cmap"]
for ch, name in cmap.getBestCmap().items():
    ch_to_name["{:04X}".format(ch)] = name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 2015-06-07
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    相关资源
    最近更新 更多