Skip to content

Commit

Permalink
Merge pull request #3785 from radarhere/unicode_path
Browse files Browse the repository at this point in the history
Fixed loading font with non-Unicode path on Windows
  • Loading branch information
hugovk committed May 4, 2019
2 parents d7bf918 + 4e6aa7d commit e20228a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
10 changes: 10 additions & 0 deletions Tests/test_imagefont.py
Expand Up @@ -7,6 +7,7 @@
import sys
import copy
import re
import shutil
import distutils.version

FONT_PATH = "Tests/fonts/FreeMono.ttf"
Expand Down Expand Up @@ -131,6 +132,15 @@ def test_font_with_open_file(self):
with open(FONT_PATH, 'rb') as f:
self._render(f)

def test_non_unicode_path(self):
try:
tempfile = self.tempfile("temp_"+chr(128)+".ttf")
except UnicodeEncodeError:
self.skipTest("Unicode path could not be created")
shutil.copy(FONT_PATH, tempfile)

ImageFont.truetype(tempfile, FONT_SIZE)

def _render(self, font):
txt = "Hello World!"
ttf = ImageFont.truetype(font, FONT_SIZE,
Expand Down
19 changes: 16 additions & 3 deletions src/PIL/ImageFont.py
Expand Up @@ -140,13 +140,26 @@ def __init__(self, font=None, size=10, index=0, encoding="",

self.layout_engine = layout_engine

def load_from_bytes(f):
self.font_bytes = f.read()
self.font = core.getfont(
"", size, index, encoding, self.font_bytes, layout_engine)

if isPath(font):
if sys.platform == "win32":
font_bytes_path = font if isinstance(font, bytes) else font.encode()
try:
font_bytes_path.decode('ascii')
except UnicodeDecodeError:
# FreeType cannot load fonts with non-ASCII characters on Windows
# So load it into memory first
with open(font, 'rb') as f:
load_from_bytes(f)
return
self.font = core.getfont(font, size, index, encoding,
layout_engine=layout_engine)
else:
self.font_bytes = font.read()
self.font = core.getfont(
"", size, index, encoding, self.font_bytes, layout_engine)
load_from_bytes(font)

def _multiline_split(self, text):
split_character = "\n" if isinstance(text, str) else b"\n"
Expand Down

0 comments on commit e20228a

Please sign in to comment.