Merge pull request #1 from hugovk/aeroaks

Remove duplication and add partial test
This commit is contained in:
aeroaks 2014-06-02 10:26:16 +05:30
commit 4dc3dc1af2
2 changed files with 52 additions and 32 deletions

View File

@ -29,13 +29,15 @@ from __future__ import print_function
from PIL import Image from PIL import Image
from PIL._util import isDirectory, isPath from PIL._util import isDirectory, isPath
import os, sys import os
import sys
try: try:
import warnings import warnings
except ImportError: except ImportError:
warnings = None warnings = None
class _imagingft_not_installed: class _imagingft_not_installed:
# module placeholder # module placeholder
def __getattr__(self, id): def __getattr__(self, id):
@ -113,6 +115,7 @@ class ImageFont:
self.getsize = self.font.getsize self.getsize = self.font.getsize
self.getmask = self.font.getmask self.getmask = self.font.getmask
## ##
# Wrapper for FreeType fonts. Application code should use the # Wrapper for FreeType fonts. Application code should use the
# <b>truetype</b> factory function to create font objects. # <b>truetype</b> factory function to create font objects.
@ -131,7 +134,8 @@ class FreeTypeFont:
self.font = core.getfont(font, size, index, encoding) self.font = core.getfont(font, size, index, encoding)
else: else:
self.font_bytes = font.read() self.font_bytes = font.read()
self.font = core.getfont("", size, index, encoding, self.font_bytes) self.font = core.getfont(
"", size, index, encoding, self.font_bytes)
def getname(self): def getname(self):
return self.font.family, self.font.style return self.font.family, self.font.style
@ -154,6 +158,7 @@ class FreeTypeFont:
self.font.render(text, im.id, mode == "1") self.font.render(text, im.id, mode == "1")
return im, offset return im, offset
## ##
# Wrapper that creates a transposed font from any existing font # Wrapper that creates a transposed font from any existing font
# object. # object.
@ -207,7 +212,8 @@ def truetype(font=None, size=10, index=0, encoding="", filename=None):
:param filename: A truetype font file. Under Windows, if the file :param filename: A truetype font file. Under Windows, if the file
is not found in this filename, the loader also looks in is not found in this filename, the loader also looks in
Windows :file:`fonts/` directory. Windows :file:`fonts/` and Linux :file:`XDG_DATA_DIRS`
directories.
:param size: The requested size, in points. :param size: The requested size, in points.
:param index: Which font face to load (default is first available face). :param index: Which font face to load (default is first available face).
:param encoding: Which font encoding to use (default is Unicode). Common :param encoding: Which font encoding to use (default is Unicode). Common
@ -227,19 +233,17 @@ def truetype(font=None, size=10, index=0, encoding="", filename=None):
try: try:
return FreeTypeFont(font, size, index, encoding) return FreeTypeFont(font, size, index, encoding)
except IOError: except IOError:
dir = None
if sys.platform == "win32": if sys.platform == "win32":
# check the windows font repository # check the windows font repository
# NOTE: must use uppercase WINDIR, to work around bugs in # NOTE: must use uppercase WINDIR, to work around bugs in
# 1.5.2's os.environ.get() # 1.5.2's os.environ.get()
windir = os.environ.get("WINDIR") dir = os.environ.get("WINDIR")
if windir:
filename = os.path.join(windir, "fonts", font)
return FreeTypeFont(filename, size, index, encoding)
elif sys.platform == "linux": elif sys.platform == "linux":
# check the linux font repository # check the Linux font repository
lindir = os.environ.get("XDG_DATA_DIRS") dir = os.environ.get("XDG_DATA_DIRS")
if lindir: if dir:
filename = os.path.join(lindir, "fonts", font) filename = os.path.join(dir, "fonts", font)
return FreeTypeFont(filename, size, index, encoding) return FreeTypeFont(filename, size, index, encoding)
raise raise
@ -401,7 +405,7 @@ w7IkEbzhVQAAAABJRU5ErkJggg==
if __name__ == "__main__": if __name__ == "__main__":
# create font data chunk for embedding # create font data chunk for embedding
import base64, os, sys import base64
font = "../Images/courB08" font = "../Images/courB08"
print(" f._load_pilfont_data(") print(" f._load_pilfont_data(")
print(" # %s" % os.path.basename(font)) print(" # %s" % os.path.basename(font))

View File

@ -15,21 +15,26 @@ from PIL import ImageDraw
font_path = "Tests/fonts/FreeMono.ttf" font_path = "Tests/fonts/FreeMono.ttf"
font_size = 20 font_size = 20
def test_sanity(): def test_sanity():
assert_match(ImageFont.core.freetype2_version, "\d+\.\d+\.\d+$") assert_match(ImageFont.core.freetype2_version, "\d+\.\d+\.\d+$")
def test_font_with_name(): def test_font_with_name():
assert_no_exception(lambda: ImageFont.truetype(font_path, font_size)) assert_no_exception(lambda: ImageFont.truetype(font_path, font_size))
assert_no_exception(lambda: _render(font_path)) assert_no_exception(lambda: _render(font_path))
_clean() _clean()
def _font_as_bytes(): def _font_as_bytes():
with open(font_path, 'rb') as f: with open(font_path, 'rb') as f:
font_bytes = BytesIO(f.read()) font_bytes = BytesIO(f.read())
return font_bytes return font_bytes
def test_font_with_filelike(): def test_font_with_filelike():
assert_no_exception(lambda: ImageFont.truetype(_font_as_bytes(), font_size)) assert_no_exception(
lambda: ImageFont.truetype(_font_as_bytes(), font_size))
assert_no_exception(lambda: _render(_font_as_bytes())) assert_no_exception(lambda: _render(_font_as_bytes()))
# Usage note: making two fonts from the same buffer fails. # Usage note: making two fonts from the same buffer fails.
# shared_bytes = _font_as_bytes() # shared_bytes = _font_as_bytes()
@ -37,13 +42,18 @@ def test_font_with_filelike():
# assert_exception(Exception, lambda: _render(shared_bytes)) # assert_exception(Exception, lambda: _render(shared_bytes))
_clean() _clean()
def test_font_with_open_file(): def test_font_with_open_file():
with open(font_path, 'rb') as f: with open(font_path, 'rb') as f:
assert_no_exception(lambda: _render(f)) assert_no_exception(lambda: _render(f))
_clean() _clean()
def test_font_old_parameters(): def test_font_old_parameters():
assert_warning(DeprecationWarning, lambda: ImageFont.truetype(filename=font_path, size=font_size)) assert_warning(
DeprecationWarning,
lambda: ImageFont.truetype(filename=font_path, size=font_size))
def _render(font): def _render(font):
txt = "Hello World!" txt = "Hello World!"
@ -56,9 +66,11 @@ def _render(font):
img.save('font.png') img.save('font.png')
return img return img
def _clean(): def _clean():
os.unlink('font.png') os.unlink('font.png')
def test_render_equal(): def test_render_equal():
img_path = _render(font_path) img_path = _render(font_path)
with open(font_path, 'rb') as f: with open(font_path, 'rb') as f:
@ -80,7 +92,6 @@ def test_render_multiline():
draw.text((0, y), line, font=ttf) draw.text((0, y), line, font=ttf)
y += line_spacing y += line_spacing
target = 'Tests/images/multiline_text.png' target = 'Tests/images/multiline_text.png'
target_img = Image.open(target) target_img = Image.open(target)
@ -133,3 +144,8 @@ def test_unrotated_transposed_font():
assert_equal(box_size_a, box_size_b) assert_equal(box_size_a, box_size_b)
def test_font_not_found():
assert_exception(IOError, lambda: ImageFont.truetype("/fake/font.ttf"))
# End of file