Pillow/Tests/test_imagefont.py

88 lines
2.4 KiB
Python
Raw Normal View History

from tester import *
from PIL import Image
2013-04-25 23:45:12 +04:00
from io import BytesIO
import os
2013-04-25 23:25:06 +04:00
try:
from PIL import ImageFont
ImageFont.core.getfont # check if freetype is available
except ImportError:
skip()
2013-04-26 08:58:04 +04:00
from PIL import ImageDraw
font_path = "Tests/fonts/FreeMono.ttf"
font_size=20
def test_sanity():
assert_match(ImageFont.core.freetype2_version, "\d+\.\d+\.\d+$")
2013-04-25 20:48:43 +04:00
def test_font_with_name():
2013-04-26 08:58:04 +04:00
assert_no_exception(lambda: ImageFont.truetype(font_path, font_size))
assert_no_exception(lambda: _render(font_path))
_clean()
2013-04-25 20:48:43 +04:00
2013-04-26 08:58:04 +04:00
def _font_as_bytes():
with open(font_path, 'rb') as f:
font_bytes = BytesIO(f.read())
return font_bytes
2013-04-25 20:48:43 +04:00
def test_font_with_filelike():
2013-04-26 08:58:04 +04:00
assert_no_exception(lambda: ImageFont.truetype(_font_as_bytes(), font_size))
assert_no_exception(lambda: _render(_font_as_bytes()))
# Usage note: making two fonts from the same buffer fails.
#shared_bytes = _font_as_bytes()
#assert_no_exception(lambda: _render(shared_bytes))
#assert_exception(Exception, lambda: _render(shared_bytes))
2013-09-25 01:23:43 +04:00
_clean()
2013-04-25 20:48:43 +04:00
2013-04-26 08:58:04 +04:00
def test_font_with_open_file():
with open(font_path, 'rb') as f:
assert_no_exception(lambda: _render(f))
_clean()
2013-04-25 20:48:43 +04:00
def test_font_old_parameters():
2013-04-26 08:58:04 +04:00
assert_warning(DeprecationWarning, lambda: ImageFont.truetype(filename=font_path, size=font_size))
def _render(font):
txt = "Hello World!"
ttf = ImageFont.truetype(font, font_size)
w, h = ttf.getsize(txt)
img = Image.new("RGB", (256, 64), "white")
d = ImageDraw.Draw(img)
d.text((10, 10), txt, font=ttf, fill='black')
img.save('font.png')
return img
def _clean():
os.unlink('font.png')
2013-04-26 08:58:04 +04:00
def test_render_equal():
img_path = _render(font_path)
with open(font_path, 'rb') as f:
font_filelike = BytesIO(f.read())
img_filelike = _render(font_filelike)
2013-04-25 20:48:43 +04:00
2013-04-26 08:58:04 +04:00
assert_image_equal(img_path, img_filelike)
_clean()
2013-09-25 01:23:17 +04:00
def test_render_multiline():
im = Image.new(mode='RGB', size=(300,100))
ttf = ImageFont.truetype(font_path, font_size)
draw = ImageDraw.Draw(im)
line_spacing = draw.textsize('A', font=ttf)[1] + 8
lines = ['hey you', 'you are awesome', 'this looks awkward']
y = 0
for line in lines:
draw.text((0, y), line, font=ttf)
y += line_spacing
target = 'Tests/images/multiline_text.png'
target_img = Image.open(target)
assert_image_equal(im, target_img)