This commit is contained in:
Andrew Murray 2025-09-08 14:43:19 +00:00 committed by GitHub
commit 16569d4bb0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 20 additions and 7 deletions

View File

@ -492,6 +492,11 @@ def test_stroke_mask() -> None:
assert mask.getpixel((42, 5)) == 255
def test_load_invalid_file() -> None:
with pytest.raises(SyntaxError, match="Not a PILfont file"):
ImageFont.load("Tests/images/1_trns.png")
def test_load_when_image_not_found() -> None:
with tempfile.NamedTemporaryFile(delete=False) as tmp:
pass

View File

@ -30,6 +30,14 @@ def test_default_font(font: ImageFont.ImageFont) -> None:
assert_image_equal_tofile(im, "Tests/images/default_font.png")
def test_invalid_mode() -> None:
font = ImageFont.ImageFont()
fp = BytesIO()
with Image.open("Tests/images/hopper.png") as im:
with pytest.raises(TypeError, match="invalid font image mode"):
font._load_pilfont_data(fp, im)
def test_without_freetype() -> None:
original_core = ImageFont.core
if features.check_module("freetype2"):

View File

@ -125,11 +125,16 @@ class ImageFont:
image.close()
def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None:
# check image
if image.mode not in ("1", "L"):
msg = "invalid font image mode"
raise TypeError(msg)
# read PILfont header
if file.readline() != b"PILfont\n":
if file.read(8) != b"PILfont\n":
msg = "Not a PILfont file"
raise SyntaxError(msg)
file.readline().split(b";")
file.readline()
self.info = [] # FIXME: should be a dictionary
while True:
s = file.readline()
@ -140,11 +145,6 @@ class ImageFont:
# read PILfont metrics
data = file.read(256 * 20)
# check image
if image.mode not in ("1", "L"):
msg = "invalid font image mode"
raise TypeError(msg)
image.load()
self.font = Image.core.font(image.im, data)