콘텐츠로 이동

이미지 서비스 API

astro:assets은 모든 이미지 최적화 서비스가 Astro 위에 서비스를 쉽게 구축할 수 있도록 설계되었습니다.

이미지 서비스란 무엇입니까?

Astro는 로컬과 외부라는 두 가지 유형의 이미지 서비스를 제공합니다.

  • 로컬 서비스는 정적 사이트의 빌드 시 또는 개발 모드와 요청 시 렌더링 모두에서 런타임 시 이미지 변환을 직접 처리합니다. 이는 Sharp, ImageMagick, Squoosh와 같은 라이브러리를 둘러싼 래퍼인 경우가 많습니다. 개발 모드와 요청 시 렌더링된 프로덕션 라우트에서 로컬 서비스는 API 엔드포인트를 사용하여 변환을 수행합니다.
  • 외부 서비스는 URL을 가리키며 Cloudinary, Vercel 또는 모든 RIAPI 호환 서버와 같은 서비스에 대한 지원을 추가할 수 있습니다.

이미지 서비스 API를 사용하여 빌드

서비스 정의는 다양한 필수 방법 ("후크")을 사용하여 내보낸 기본 객체의 형태를 취합니다.

외부 서비스는 출력 <img> 태그의 src를 가리키는 getURL()을 제공합니다.

로컬 서비스는 이미지 변환을 수행하는 transform() 메서드와 개발 모드 및 요청 시 렌더링용 엔드포인트를 사용하는 getURL()parseURL() 메서드를 제공합니다.

두 유형의 서비스 모두 getHTMLAttributes()를 제공하여 출력 <img>의 다른 속성을 결정하고 validateOptions()를 제공하여 전달된 옵션을 검증하고 강화할 수 있습니다.

외부 서비스

외부 서비스는 최종 <img> 태그의 src 속성으로 사용될 원격 URL을 가리킵니다. 이 원격 URL은 이미지 다운로드, 변환 및 반환을 담당합니다.

import type { ExternalImageService, ImageTransform, AstroConfig } from "astro";

const service: ExternalImageService = {
  validateOptions(options: ImageTransform, imageConfig: AstroConfig['image']) {
    const serviceConfig = imageConfig.service.config;

    // 사용자가 설정한 최대 너비를 적용합니다.
    if (options.width && options.width > serviceConfig.maxWidth) {
      console.warn(`Image width ${options.width} exceeds max width ${serviceConfig.maxWidth}. Falling back to max width.`);
      options.width = serviceConfig.maxWidth;
    }

    return options;
  },
  getURL(options, imageConfig) {
    return `https://mysupercdn.com/${options.src}?q=${options.quality}&w=${options.width}&h=${options.height}`;
  },
  getHTMLAttributes(options, imageConfig) {
    const { src, format, quality, ...attributes } = options;
		return {
			...attributes,
			loading: options.loading ?? 'lazy',
			decoding: options.decoding ?? 'async',
		};
	}
};


export default service;

로컬 서비스

자신만의 로컬 서비스를 생성하려면 내장된 엔드포인트 (/_image)를 가리키거나 서비스의 메서드를 호출할 수 있는 자체 엔드포인트를 추가로 생성할 수 있습니다.

import type { ImageTransform, LocalImageService, AstroConfig } from "astro";

const service: LocalImageService<AstroConfig["image"]> = {
  getURL(options: ImageTransform, imageConfig) {
    const searchParams = new URLSearchParams();
		searchParams.append('href', typeof options.src === "string" ? options.src : options.src.src);
		options.width && searchParams.append('w', options.width.toString());
		options.height && searchParams.append('h', options.height.toString());
		options.quality && searchParams.append('q', options.quality.toString());
		options.format && searchParams.append('f', options.format);
    return `/my_custom_endpoint_that_transforms_images?${searchParams}`;
    // 또는 내장된 엔드포인트를 사용하여 parsURL 및 변환 함수를 호출합니다.
    // 이 함수는 `/_image?${searchParams}`를 반환합니다.
  },
  parseURL(url: URL, imageConfig) {
    const params = url.searchParams;
    return {
      src: params.get('href')!,
      width: params.has('w') ? parseInt(params.get('w')!) : undefined,
      height: params.has('h') ? parseInt(params.get('h')!) : undefined,
			format: params.get('f'),
      quality: params.get('q'),
    };
  },
  async transform(inputBuffer: Uint8Array, options: { src: string, [key: string]: any }, imageConfig) {
    const { buffer } = await mySuperLibraryThatEncodesImages(options);
    return {
      data: buffer,
      format: options.format,
    };
  },
  getHTMLAttributes(options, imageConfig) {
		let targetWidth = options.width;
		let targetHeight = options.height;
		if (typeof options.src === "object") {
			const aspectRatio = options.src.width / options.src.height;

			if (targetHeight && !targetWidth) {
				targetWidth = Math.round(targetHeight * aspectRatio);
			} else if (targetWidth && !targetHeight) {
				targetHeight = Math.round(targetWidth / aspectRatio);
			}
		}

		const { src, width, height, format, quality, ...attributes } = options;

		return {
			...attributes,
			width: targetWidth,
			height: targetHeight,
			loading: attributes.loading ?? 'lazy',
			decoding: attributes.decoding ?? 'async',
		};
	},
	propertiesToHash: ['src', 'width', 'height', 'format', 'quality'],
};
export default service;

정적 사이트와 사전 렌더링된 경로 빌드 시 <Image />getImage(options)는 모두 transform() 함수를 호출합니다. 각각 컴포넌트의 속성이나 options 인수를 통해 옵션을 전달합니다. 변환된 이미지는 dist/_astro 폴더에 빌드됩니다. 파일 이름에는 propertiesToHash에 전달된 속성의 해시가 포함됩니다. 이 속성은 선택 사항이며 기본값은 ['src', 'width', 'height', 'format', 'quality']입니다. 사용자 정의 이미지 서비스에 생성된 이미지를 변경하는 추가 옵션이 있는 경우 배열에 추가합니다.

개발 모드와 요청 시 렌더링을 위해 어댑터를 사용할 때, Astro는 어떤 이미지를 최적화해야 하는지 미리 알 수 없습니다. Astro는 GET 엔드포인트 (기본적으로 /_image)를 사용하여 런타임에 이미지를 처리합니다. <Image />getImage()는 해당 옵션을 getURL()에 전달하여 엔드포인트 URL을 반환합니다. 그런 다음 엔드포인트는 parseURL()을 호출하고 결과 속성을 transform()에 전달합니다.

getConfiguredImageService & imageConfig

자체 엔드포인트를 Astro 엔드포인트로 구현하는 경우 getConfiguredImageServiceimageConfig를 사용하여 서비스의 parseURLtransform 메서드를 호출하고 이미지 구성을 제공할 수 있습니다.

이미지 서비스 구성 (image.service.config)에 액세스하려면 imageConfig.service.config를 사용할 수 있습니다.

import type { APIRoute } from "astro";
import { getConfiguredImageService, imageConfig } from 'astro:assets';

export const GET: APIRoute = async ({ request }) => {
  const imageService = await getConfiguredImageService();

  const imageTransform = imageService.parseURL(new URL(request.url), imageConfig);
  // ... imageTransform.src에서 이미지를 가져와 inputBuffer에 저장합니다.
  const { data, format } = await imageService.transform(inputBuffer, imageTransform, imageConfig);
  return new Response(data, {
			status: 200,
			headers: {
				'Content-Type': mime.getType(format) || ''
      }
    }
  );
}

전체 예시는 내장 엔드포인트를 참조하세요.

getURL()

타입: (options: ImageTransform, imageConfig: AstroConfig['image']) => string | Promise<string>

추가된 버전: astro@2.1.0

로컬 및 외부 서비스에 필요함

로컬 서비스의 경우 이 후크는 이미지를 생성하는 엔드포인트의 URL을 반환합니다 (요청 시 렌더링 및 개발 모드에서). 빌드 중에는 사용되지 않습니다. getURL()이 가리키는 로컬 엔드포인트는 parseURL()transform()을 모두 호출할 수 있습니다.

외부 서비스의 경우 이 후크는 이미지의 최종 URL을 반환합니다.

두 서비스 유형 모두 options는 사용자가 <Image /> 컴포넌트의 속성 또는 getImage()에 대한 옵션으로 전달한 속성입니다.

parseURL()

타입: (url: URL, imageConfig: AstroConfig['image']) => { src: string, [key: string]: any } | undefined | Promise<{ src: string, [key: string]: any }> | Promise<undefined>

추가된 버전: astro@2.1.0

로컬 서비스에만 필요합니다. 외부 서비스에 사용할 수 없음

이 후크는 getURL()에 의해 생성된 URL을 transform (요청 시 렌더링 및 개발 모드에서)에 사용되는 다른 속성을 가진 객체로 다시 구문 분석합니다. 빌드 중에는 사용되지 않습니다.

transform()

타입: (inputBuffer: Uint8Array, options: { src: string, [key: string]: any }, imageConfig: AstroConfig['image']) => Promise<{ data: Uint8Array; format: ImageOutputFormat }>

추가된 버전: astro@2.1.0

로컬 서비스에만 필요합니다. 외부 서비스에 사용할 수 없음

이 후크는 이미지를 변환하고 반환하며 빌드 중에 호출되어 최종 자산 파일을 생성합니다.

요청 시 렌더링 및 개발 모드에서 사용자에게 적절한 MIME 유형이 제공되도록 하려면 format을 반환해야 합니다.

getHTMLAttributes()

타입: (options: ImageTransform, imageConfig: AstroConfig['image'] ) => Record<string, any> | Promise<Record<string, any>>

추가된 버전: astro@2.1.0

로컬 및 외부 서비스 모두 선택 사항

이 후크는 사용자가 전달한 매개변수 (options)를 기반으로 이미지를 HTML로 렌더링하는 데 사용되는 모든 추가 속성을 반환합니다.

getSrcSet()

타입: (options: ImageTransform, imageConfig: AstroConfig['image'] ) => UnresolvedSrcSetValue[] | Promise<UnresolvedSrcSetValue[]>

추가된 버전: astro@3.3.0

로컬 및 외부 서비스 모두 선택 사항입니다.

이 후크는 <img> 또는 <picture>sourcesrcset 속성을 생성하기 위해 지정된 이미지의 여러 변형을 생성합니다.

이 후크는 다음 속성을 가진 객체 배열을 반환합니다.

export type UnresolvedSrcSetValue = {
	transform: ImageTransform;
	descriptor?: string;
	attributes?: Record<string, any>;
};

validateOptions()

타입: (options: ImageTransform, imageConfig: AstroConfig['image'] ) => ImageTransform | Promise<ImageTransform>

추가된 버전: astro@2.1.4

로컬 및 외부 서비스 모두 선택 사항

이 후크를 사용하면 사용자가 전달한 옵션을 검증하고 강화할 수 있습니다. 이는 기본 옵션을 설정하거나 사용자에게 매개변수가 필요함을 알리는 데 유용합니다.

Astro 내장 서비스에서 validateOptions()가 어떻게 사용되는지 확인하세요.

getRemoteSize()

Type: (url: string, imageConfig: AstroConfig['image'] ) => Omit<ImageMetadata, 'src' | 'fsPath'> | Promise<Omit<ImageMetadata, 'src' | 'fsPath'>>

추가된 버전: astro@6.0.0

로컬 및 외부 서비스 모두 선택 사항

이 훅을 사용하면 inferRemoteSize()의 동작을 확장할 수 있습니다. 이는 이미지를 캐싱하여 네트워크 트래픽을 줄이거나, 이미지 URL에서 이미지 정보를 예측할 수 있는 경우에 유용합니다.

사용자 구성

astro.config.mjs 파일에서 사용할 이미지 서비스를 구성합니다. 구성은 다음 형식을 취합니다.

import { defineConfig } from "astro/config";

export default defineConfig({
  image: {
    service: {
      entrypoint: "your-entrypoint", // 'astro/assets/services/sharp' | string,
      config: {
        // ... 서비스별 구성. 선택적.
      }
    }
  },
});

사용자 정의 이미지 서비스 props 타이핑

사용자 이미지 서비스가 Astro의 <Image> 컴포넌트, <Picture> 컴포넌트 또는 getImage() 함수에 추가 props를 지원하는 경우, Astro.CustomImageProps 인터페이스를 확장하여 해당 props에 대한 타입을 추가할 수 있습니다.

다음은 이미지 서비스가 지원하는 사용자 정의 blur prop을 추가하는 예시입니다.

declare namespace Astro {
  interface CustomImageProps {
    /** 이 반경으로 이미지에 가우시안 블러를 적용합니다. */
    blur?: number;
  }
}

이미지 서비스를 Astro 통합으로 만들고 injectTypes() 도우미를 사용하여 이러한 타입을 사용자에게 노출할 수 있습니다.

그러면 사용자는 사용자 정의 props에 대해 자동 완성 및 타입 안전성을 얻을 수 있습니다.

<Image blur="yes" src={myPhoto}  />
//     ^^^^^^^^^^
//     Type 'string' is not assignable to type 'number | undefined'.
기여하기 커뮤니티 후원하기