diff --git a/Tests/fonts/10x20-ISO8859-1-fewer-characters.pcf b/Tests/fonts/10x20-ISO8859-1-fewer-characters.pcf new file mode 100644 index 000000000..c065f59a9 Binary files /dev/null and b/Tests/fonts/10x20-ISO8859-1-fewer-characters.pcf differ diff --git a/Tests/test_font_pcf.py b/Tests/test_font_pcf.py index 288848f26..92ed60362 100644 --- a/Tests/test_font_pcf.py +++ b/Tests/test_font_pcf.py @@ -49,6 +49,14 @@ def test_sanity(request, tmp_path): save_font(request, tmp_path) +def test_less_than_256_characters(): + with open("Tests/fonts/10x20-ISO8859-1-fewer-characters.pcf", "rb") as test_file: + font = PcfFontFile.PcfFontFile(test_file) + assert isinstance(font, FontFile.FontFile) + # check the number of characters in the font + assert len([_f for _f in font.glyph if _f]) == 127 + + def test_invalid_file(): with open("Tests/images/flower.jpg", "rb") as fp: with pytest.raises(SyntaxError): diff --git a/src/PIL/PcfFontFile.py b/src/PIL/PcfFontFile.py index 0b43b27ac..442ac70c4 100644 --- a/src/PIL/PcfFontFile.py +++ b/src/PIL/PcfFontFile.py @@ -84,8 +84,7 @@ class PcfFontFile(FontFile.FontFile): # # create glyph structure - for ch in range(256): - ix = encoding[ch] + for ch, ix in enumerate(encoding): if ix is not None: x, y, l, r, w, a, d, f = metrics[ix] glyph = (w, 0), (l, d - y, x + l, d), (0, 0, x, y), bitmaps[ix] @@ -219,10 +218,6 @@ class PcfFontFile(FontFile.FontFile): return bitmaps def _load_encoding(self): - - # map character code to bitmap index - encoding = [None] * 256 - fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS) first_col, last_col = i16(fp.read(2)), i16(fp.read(2)) @@ -232,6 +227,9 @@ class PcfFontFile(FontFile.FontFile): nencoding = (last_col - first_col + 1) * (last_row - first_row + 1) + # map character code to bitmap index + encoding = [None] * min(256, nencoding) + encoding_offsets = [i16(fp.read(2)) for _ in range(nencoding)] for i in range(first_col, len(encoding)): @@ -244,7 +242,5 @@ class PcfFontFile(FontFile.FontFile): except UnicodeDecodeError: # character is not supported in selected encoding pass - except IndexError: - break return encoding