Commit ac6ec8d

HPCesia <me@hpcesia.com>
2025-08-21 07:12:02
feat: cache infered remote image size
1 parent 4544a20
Changed files (3)
src/components/utils/ImageWrapper.astro
@@ -1,7 +1,8 @@
 ---
 import { buildConfig } from '@/config';
+import { getCachedRemoteImageSize } from '@/utils/image-size-cache';
 import type { ImageMetadata } from 'astro';
-import { Image, inferRemoteSize } from 'astro:assets';
+import { Image } from 'astro:assets';
 import path from 'path';
 
 interface Props {
@@ -51,12 +52,11 @@ if (isLocal) {
 
 let w, h;
 if (isRemote && buildConfig.inferRemoteImageSize.enable) {
-  try {
-    const { width, height } = await inferRemoteSize(src as string);
-    w = width;
-    h = height;
-  } catch {
-    console.error(`\n[ERROR] Infer remote image size faild: ${src}`);
+  const dimensions = await getCachedRemoteImageSize(src);
+  if (dimensions) {
+    w = dimensions.width;
+    h = dimensions.height;
+  } else {
     w = buildConfig.inferRemoteImageSize.defaultSize.width;
     h = buildConfig.inferRemoteImageSize.defaultSize.height;
   }
src/components/utils/Markdown.astro
@@ -1,8 +1,8 @@
 ---
 import { buildConfig } from '@/config';
 import '@/styles/markdown.css';
+import { getCachedRemoteImageSize } from '@/utils/image-size-cache';
 import type { HTMLAttributes } from 'astro/types';
-import { inferRemoteSize } from 'astro:assets';
 import { load as cheerioLoad } from 'cheerio';
 import crypto from 'crypto';
 import type PhotoSwipeLightbox from 'photoswipe/lightbox';
@@ -73,14 +73,10 @@ const imageZoomReplacer = !buildConfig.enableImageZoom
             !src.startsWith('/') &&
             buildConfig.inferRemoteImageSize.enable
           ) {
-            try {
-              const metadata = await inferRemoteSize(src);
-              width = metadata.width;
-              height = metadata.height;
-            } catch (error) {
-              console.warn(
-                `[WARN] Could not infer size for image "${src}": ${(error as Error).message}.`
-              );
+            const dimensions = await getCachedRemoteImageSize(src);
+            if (dimensions) {
+              width = dimensions.width;
+              height = dimensions.height;
             }
           }
           if (width && height) {
src/utils/image-size-cache.ts
@@ -0,0 +1,25 @@
+import { inferRemoteSize } from 'astro:assets';
+
+const cache = new Map<string, { width: number; height: number }>();
+
+export async function getCachedRemoteImageSize(
+  src: string
+): Promise<{ width: number; height: number } | null> {
+  if (cache.has(src)) {
+    return cache.get(src)!;
+  }
+
+  try {
+    const metadata = await inferRemoteSize(src);
+    const dimensions = { width: metadata.width, height: metadata.height };
+
+    cache.set(src, dimensions);
+
+    return dimensions;
+  } catch (error) {
+    console.warn(
+      `[WARN] Could not infer size for image "${src}": ${(error as Error).message}.`
+    );
+    return null;
+  }
+}