From 612e3c24a4f38837a6d915fe8eac15a7d1eeca17 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 6 Feb 2026 21:39:39 +1100 Subject: [PATCH] Remove temporary buffer --- src/PIL/FontFile.py | 39 +++++++++++++++++++++------------------ src/PIL/ImageFont.py | 3 +++ 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/src/PIL/FontFile.py b/src/PIL/FontFile.py index 71a08b05e..c0c64fe68 100644 --- a/src/PIL/FontFile.py +++ b/src/PIL/FontFile.py @@ -15,7 +15,6 @@ # from __future__ import annotations -import io import os from typing import BinaryIO @@ -111,6 +110,22 @@ class FontFile: self.bitmap.paste(im.crop(src), s) self.metrics[i] = d, dst, s + def _encode_metrics(self) -> bytes: + values: tuple[int, ...] = () + for id in range(256): + m = self.metrics[id] + if m: + values += m[0] + m[1] + m[2] + else: + values += (0,) * 10 + + metrics = b"" + for v in values: + if v < 0: + v += 65536 + metrics += _binary.o16be(v) + return metrics + def save(self, filename: str) -> None: """Save font""" @@ -124,19 +139,10 @@ class FontFile: # font metrics with open(os.path.splitext(filename)[0] + ".pil", "wb") as fp: - self.save_metrics(fp) - - def save_metrics(self, fp: BinaryIO) -> None: - """Save font metrics to a file-like object""" - fp.write(b"PILfont\n") - fp.write(f";;;;;;{self.ysize};\n".encode("ascii")) # HACK!!! - fp.write(b"DATA\n") - for id in range(256): - m = self.metrics[id] - if not m: - puti16(fp, (0,) * 10) - else: - puti16(fp, m[0] + m[1] + m[2]) + fp.write(b"PILfont\n") + fp.write(f";;;;;;{self.ysize};\n".encode("ascii")) # HACK!!! + fp.write(b"DATA\n") + fp.write(self._encode_metrics()) def to_imagefont(self) -> ImageFont.ImageFont: """Convert to ImageFont""" @@ -148,9 +154,6 @@ class FontFile: msg = "No bitmap created" raise ValueError(msg) - buf = io.BytesIO() - self.save_metrics(buf) - buf.seek(0) imagefont = ImageFont.ImageFont() - imagefont._load_pilfont_data(buf, self.bitmap) + imagefont._load(self.bitmap, self._encode_metrics()) return imagefont diff --git a/src/PIL/ImageFont.py b/src/PIL/ImageFont.py index ae003d139..ea7f4dc54 100644 --- a/src/PIL/ImageFont.py +++ b/src/PIL/ImageFont.py @@ -149,6 +149,9 @@ class ImageFont: # read PILfont metrics data = file.read(256 * 20) + self._load(image, data) + + def _load(self, image: Image.Image, data: bytes) -> None: image.load() self.font = Image.core.font(image.im, data)