Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed loading font with non-Unicode path on Windows #3785

Merged
merged 1 commit into from May 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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