From b3cb19fa1d9feb4c4358110d9ce876502879f513 Mon Sep 17 00:00:00 2001 From: "John Li (Tet)" Date: Fri, 10 Feb 2023 23:40:12 -0800 Subject: [PATCH] added font caching --- ImageScript.js | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/ImageScript.js b/ImageScript.js index b43b3a0..523a234 100644 --- a/ImageScript.js +++ b/ImageScript.js @@ -18,6 +18,22 @@ const MAGIC_NUMBERS = { TIFF: 0x49492a00, GIF: 0x474946 }; +const initFontLib = fontlib.init(); +const fontScaleCache = new Map(); // > +const getFont= async (font,scale) =>{ + const { Font, Layout } = await initFontLib; + let scaleCache = fontScaleCache.get(scale) + if (!scaleCache) { + scaleCache = new Map() + fontScaleCache.set(scale,scaleCache) + scaleCache.set(font, new Font(scale, font)) + } + let fontCache = scaleCache.get(font) + if (!fontCache) { + scaleCache.set(font, new Font(scale, font)) + } + return scaleCache.get(font) +} /** * Represents an image; provides utility functions @@ -1185,11 +1201,11 @@ class Image { * @return {Promise} The rendered text */ static async renderText(font, scale, text, color = 0xffffffff, layout = new TextLayout()) { - const { Font, Layout } = await fontlib.init(); - font = new Font(scale, font); - const [r, g, b, a] = Image.colorToRGBA(color); + font = await getFont(font,scale) + const [r, g, b, a] = Image.colorToRGBA(color); + const Layout = (await initFontLib).Layout; const layoutOptions = new Layout(); layoutOptions.reset({ @@ -1210,7 +1226,7 @@ class Image { if (image.height > layout.maxHeight) image.crop(0, 0, image.width, Math.floor(layoutOptions.lines() / image.height * layout.maxHeight) * (image.height / layoutOptions.lines())); - font.free(); + // font.free(); layoutOptions.free(); return image.opacity(a / 0xff); }