惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
IT之家
IT之家
博客园_首页
人人都是产品经理
人人都是产品经理
博客园 - Franky
I
InfoQ
Recent Announcements
Recent Announcements
P
Proofpoint News Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
GbyAI
GbyAI
大猫的无限游戏
大猫的无限游戏
aimingoo的专栏
aimingoo的专栏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
月光博客
月光博客
Microsoft Security Blog
Microsoft Security Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
B
Blog RSS Feed
MongoDB | Blog
MongoDB | Blog
雷峰网
雷峰网
博客园 - 聂微东
N
Netflix TechBlog - Medium
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The GitHub Blog
The GitHub Blog
D
Docker

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN
Two Issues Related to ImageFont Module in PIL
2018-12-04 · via jdhao's digital space

In this post, I want to write about two issues related to the ImageFont module in the PIL package.

Can not use non-ASCII characters in font path on Windows#

On Windows, if you use non-ASCII characters in font path in ImageFont.truetype() method, you will get the following error:

OSError                                   Traceback (most recent call last)
<ipython-input-2-72cffff24bf9> in <module>()
----> 1 font = ImageFont.truetype("../测试.ttf")

D:\Anaconda\lib\site-packages\PIL\ImageFont.py in truetype(font, size, index, encoding, layout_engine)
    278
    279     try:
--> 280         return FreeTypeFont(font, size, index, encoding, layout_engine)
    281     except IOError:
    282         ttf_filename = os.path.basename(font)

D:\Anaconda\lib\site-packages\PIL\ImageFont.py in __init__(self, font, size, index, encoding, layout_engine)
    143         if isPath(font):
    144             self.font = core.getfont(font, size, index, encoding,
--> 145                                      layout_engine=layout_engine)
    146         else:
    147             self.font_bytes = font.read()

OSError: cannot open resource

This is an issue related to how Unicode file paths are handled on Windows platform.

A simple solution is to rename the font file to include only ASCII characters. Another solution is to read the font file in binary form. A working example is shown below:

from PIL import ImageFont
from io import BytesIO

with open("测试.ttf", "rb") as f:
    bytes_font = BytesIO(f.read())
font = ImageFont.truetype(bytes_font)
print(font.getsize("test"))

Invalid reference when drawing text on image#

When drawing text on image using PIL, you may see an error complaining about invalid reference:

python draw_text.py
Traceback (most recent call last):
File "draw_text.py", line 12, in <module>
    drawer.text((10, 10), "大美中國", font=font, fill=(10, 10, 10))
File "D:\Anaconda\lib\site-packages\PIL\ImageDraw.py", line 275, in text
    *args, **kwargs)
File "D:\Anaconda\lib\site-packages\PIL\ImageFont.py", line 185, in getmask2
    size, offset = self.font.getsize(text, direction, features)
OSError: invalid reference

This is caused by a missing table in the font, which is discussed here. To fix this problem, we need to use the open-source tool ttfautohint.

After downloading this tool, we can process the font to get a fixed font:

ttfautohint test.ttf test_processed.ttf

After this process, you should be able to draw text on images using the processed font without any error.