feat: infer remote size config

This commit is contained in:
HPCesia 2025-03-24 22:17:57 +08:00
parent 7e40bf2eda
commit a3ae7b72a5
3 changed files with 43 additions and 5 deletions

View File

@ -1,7 +1,9 @@
---
import { buildConfig } from '@/config';
import type { ImageMetadata } from 'astro';
import { Image, inferRemoteSize } from 'astro:assets';
import path from 'path';
interface Props {
id?: string;
src: ImageMetadata | string;
@ -48,16 +50,19 @@ if (isLocal) {
}
let w, h;
if (isRemote) {
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}`);
w = 128;
h = 128;
w = buildConfig.inferRemoteImageSize.defaultSize.width;
h = buildConfig.inferRemoteImageSize.defaultSize.height;
}
} else {
w = buildConfig.inferRemoteImageSize.defaultSize.width;
h = buildConfig.inferRemoteImageSize.defaultSize.height;
}
const imageClass = 'w-full h-full object-cover';
@ -73,8 +78,8 @@ const imageStyle = `object-position: ${position}`;
alt={alt || ''}
class={imageClass}
style={imageStyle}
width={w!}
height={h!}
width={w}
height={h}
/>
)
}

View File

@ -41,6 +41,13 @@ export const siteConfig: SiteConfig = {
export const buildConfig: BuildConfig = {
showDraftsOnDev: true,
inferRemoteImageSize: {
enable: true,
defaultSize: {
width: 800,
height: 600,
},
},
};
export const profileConfig: ProfileConfig = {

View File

@ -186,6 +186,32 @@ export type BuildConfig = {
* 稿
*/
showDraftsOnDev: boolean;
/**
* Fetch the size data of remote images during build.\
* This feature **CAN NOT** fetch images in `.md` files.
* To fetch images in `.md` files, see https://docs.astro.build/en/reference/configuration-reference/#imageservice
*
* \
* **** `.md`
* `.md` https://docs.astro.build/zh-cn/reference/configuration-reference/#imageservice
*/
inferRemoteImageSize: {
/**
* Whether to enable the feature. Enabling this can reduce cumulative layout shift, but will increase build time.
*
*
*/
enable: boolean;
/**
* The default size of the image. This will be used when the size of the image cannot be fetched or the feature is disabled.
*
* 使
*/
defaultSize: {
width: number;
height: number;
};
};
};
export type ProfileConfig = {