콘텐츠로 이동

이미지 및 자산 API 참조

추가된 버전: astro@3.0.0

Astro는 최적화된 이미지를 표시하기 위한 기본 컴포넌트와 도우미 함수를 제공합니다. 기능 및 사용 예시는 이미지 가이드를 참조하세요.

가상 assets 모듈에서 다음 도우미를 가져옵니다.

import {
Image,
Picture,
getImage,
inferRemoteSize,
getConfiguredImageService,
imageConfig,
} from 'astro:assets';

<Image /> 컴포넌트는 이미지를 최적화하고 변환합니다.

이 컴포넌트는 컨테이너 크기 또는 기기 화면의 크기와 해상도에 따라 조정할 수 있는 반응형 이미지를 만드는 데도 사용할 수 있습니다.

src/components/MyComponent.astro
---
// Image 컴포넌트 및 이미지 가져오기
import { Image } from 'astro:assets';
import myImage from "../assets/my_image.png"; // 1600x900의 이미지
---
<!-- Image 컴포넌트에서는 'alt'가 필수입니다. -->
<Image src={myImage} alt="A description of my image." />
<!-- 결과 -->
<!-- 이미지가 최적화되었으며 적절한 속성이 적용되었습니다. -->
<img
src="/_astro/my_image.hash.webp"
width="1600"
height="900"
decoding="async"
loading="lazy"
alt="A description of my image."
/>

<Image /> 컴포넌트는 HTML의 <img> 태그가 허용하는 모든 속성 외에도 다음에 나열된 속성과 반응형 이미지 속성을 허용합니다.

타입: ImageMetadata | string | Promise<{ default: ImageMetadata }>

이미지 파일의 src 값 형식은 이미지 파일의 위치에 따라 다릅니다.

  • src/의 로컬 이미지 - 상대 파일 경로를 사용하여 이미지도 가져오거나 가져오기 별칭을 구성하고 사용해야 합니다. 그런 다음 가져오기 이름을 src 값으로 사용합니다.

    src/pages/index.astro
    ---
    import { Image } from 'astro:assets';
    import myImportedImage from '../assets/my-local-image.png';
    ---
    <Image src={myImportedImage} alt="descriptive text" />
  • public/ 폴더의 이미지 - 이미지의 public 폴더에 상대적인 파일 경로 사용:

    src/pages/index.astro
    ---
    import { Image } from 'astro:assets';
    ---
    <Image
    src="/images/my-public-image.png"
    alt="descriptive text"
    width="200"
    height="150"
    />
  • 원격 이미지 - 이미지의 전체 URL을 속성 값으로 사용합니다.

    src/pages/index.astro
    ---
    import { Image } from 'astro:assets';
    ---
    <Image
    src="https://example.com/remote-image.jpg"
    alt="descriptive text"
    width="200"
    height="150"
    />

타입: string

이미지에 대한 설명 대체 텍스트 문자열을 제공하려면 필수 alt 속성을 사용하세요.

이미지가 단지 장식용인 경우 (즉, 페이지 이해에 도움이 되지 않는 경우) alt=""를 설정하여 화면 판독기 및 기타 보조 기술이 이미지를 무시하도록 알립니다.

widthheight (public/의 이미지에 필요)

섹션 제목: “width 및 height (public/의 이미지에 필요)”

타입: number | `${number}` | undefined

이러한 속성은 이미지에 사용할 크기를 정의합니다.

layout 유형이 설정되면, 이미지의 크기에 따라 이 값들이 자동으로 생성되므로 대부분의 경우 수동으로 설정하지 않아도 됩니다.

이미지를 원본 가로세로 비율로 사용하는 경우 widthheight는 선택사항입니다. 이러한 크기는 src/에 있는 이미지 파일에서 자동으로 유추할 수 있습니다. 원격 이미지의 경우 <Image /> 또는 <Picture /> 컴포넌트의 inferSize 속성을 true로 설정하거나 inferRemoteSize() 함수를 사용하세요.

그러나 Astro는 이러한 파일을 분석할 수 없으므로 public/ 폴더에 저장된 이미지에는 이 두 속성이 모두 필요합니다.

타입: (number | `${number}x`)[] | undefined

추가된 버전: astro@3.3.0

이미지에 대해 생성할 픽셀 밀도 목록입니다.

densities 속성은 layout prop 또는 image.layout 구성 세트를 사용하는 반응형 이미지와 호환되지 않으며 설정된 경우 무시됩니다.

제공된 경우 이 값은 <img> 태그에 srcset 속성을 생성하는 데 사용됩니다. 이 값을 사용할 때 widths 값을 제공하지 마세요.

이미지 크기가 커지는 것을 방지하기 위해 원본 이미지보다 더 큰 너비와 동일한 밀도는 무시됩니다.

src/components/MyComponent.astro
---
import { Image } from 'astro:assets';
import myImage from '../assets/my_image.png';
---
<Image
src={myImage}
width={myImage.width / 2}
densities={[1.5, 2]}
alt="A description of my image."
/>
<!-- 출력 -->
<img
src="/_astro/my_image.hash.webp"
srcset="
/_astro/my_image.hash.webp 1.5x
/_astro/my_image.hash.webp 2x
"
alt="A description of my image."
width="800"
height="450"
loading="lazy"
decoding="async"
/>

타입: number[] | undefined

추가된 버전: astro@3.3.0

이미지에 대해 생성할 너비 목록입니다.

제공된 경우 이 값은 <img> 태그에 srcset 속성을 생성하는 데 사용됩니다. sizes 속성도 제공해야 합니다.

layout 속성을 사용하는 반응형 이미지는 widthssizes 속성을 자동으로 생성합니다. 일반적으로 이러한 값을 제공할 필요는 없지만 자동으로 생성된 값을 재정의하는 데 사용할 수 있습니다.

이 값을 사용할 때는 densities 값을 제공하지 마세요. 이 두 값 중 하나만 사용하여 srcset을 생성할 수 있습니다.

이미지 크기가 커지는 것을 방지하기 위해 원본 이미지보다 큰 너비는 무시됩니다.

src/components/MyComponent.astro
---
import { Image } from 'astro:assets';
import myImage from '../assets/my_image.png'; // 1600x900의 이미지
---
<Image
src={myImage}
widths={[240, 540, 720, myImage.width]}
sizes={`(max-width: 360px) 240px, (max-width: 720px) 540px, (max-width: 1600px) 720px, ${myImage.width}px`}
alt="A description of my image."
/>
<!-- 출력 -->
<img
src="/_astro/my_image.hash.webp"
srcset="
/_astro/my_image.hash.webp 240w,
/_astro/my_image.hash.webp 540w,
/_astro/my_image.hash.webp 720w,
/_astro/my_image.hash.webp 1600w
"
sizes="
(max-width: 360px) 240px,
(max-width: 720px) 540px,
(max-width: 1600px) 720px,
1600px
"
alt="A description of my image."
width="1600"
height="900"
loading="lazy"
decoding="async"
/>

타입: string | undefined

추가된 버전: astro@3.3.0

각 미디어 조건 목록에 대한 이미지의 레이아웃 너비를 지정합니다. widths를 지정할 때 반드시 제공해야 합니다.

layout 속성을 사용하는 반응형 이미지는 widthssizes 속성을 자동으로 생성합니다. 일반적으로 이러한 값을 제공할 필요는 없지만 자동으로 생성된 값을 재정의하는 데 사용할 수 있습니다.

constrainedfull-width 이미지에 대해 생성된 sizes 속성은 뷰포트가 이미지 너비보다 작은 경우 이미지가 화면 전체 너비에 가깝게 표시된다는 가정을 기반으로 합니다. 크게 다른 경우 (예: 작은 화면의 다중 열 레이아웃)에는 최상의 결과를 위해 sizes 속성을 수동으로 조정해야 할 수 있습니다.

타입: ImageOutputFormat | undefined

선택적으로 사용할 이미지 파일 형식 출력을 명시할 수 있습니다.

기본적으로 <Image /> 컴포넌트는 .webp 파일을 생성합니다.

타입: ImageQuality | undefined

quality는 다음 중 하나일 수 있는 선택적 속성입니다.

  • 형식 간 자동으로 표준화되는 사전 설정 (low, mid, high, max)입니다.
  • 0부터 100까지의 숫자 (형식에 따라 다르게 해석됨)

타입: boolean
기본값: false

추가된 버전: astro@4.4.0

원격 이미지의 원래 widthheight를 자동으로 설정할 수 있습니다.

기본적으로 이 값은 false로 설정되어 있어 원격 이미지에 두 크기를 모두 수동으로 지정해야 합니다.

<Image /> 컴포넌트에 inferSize를 추가하거나 getImage()inferSize: true를 추가하여 가져올 때 이미지 콘텐츠에서 이러한 값을 추론합니다. 이는 원격 이미지의 크기를 모르거나 변경될 수 있는 경우에 유용합니다.

src/components/MyComponent.astro
---
import { Image } from 'astro:assets';
---
<Image src="https://example.com/cat.png" inferSize alt="A cat sleeping in the sun." />

inferSize승인되지 않은 도메인의 원격 이미지의 크기를 가져올 수 있지만 이미지 자체는 처리되지 않은 상태로 유지됩니다.

타입: boolean
기본값: false

추가된 버전: astro@5.10.0

웹 페이지에 접속 시, 스크롤하지 않아도 화면에 바로 나타나는 이미지에 대해 loading, decoding, fetchpriority 속성을 최적화된 값으로 자동 설정합니다.

src/components/MyComponent.astro
---
import { Image } from 'astro:assets';
import myImage from '../assets/my_image.png';
---
<Image src={myImage} priority alt="A description of my image" />

priority="true" (또는 단축 구문 priority)를 <Image /> 또는 <Picture /> 컴포넌트에 추가하면 브라우저에 이미지를 즉시 로드하도록 지시하는 다음 속성이 추가됩니다.

loading="eager"
decoding="sync"
fetchpriority="high"

이러한 개별 속성을 사용자 정의하는 경우 수동으로 설정할 수 있습니다.

추가된 버전: astro@3.3.0

<Picture /> 컴포넌트는 여러 형식 및/또는 크기로 최적화된 이미지를 생성합니다.

이 컴포넌트는 컨테이너 크기 또는 기기 화면의 크기와 해상도에 따라 조정할 수 있는 반응형 이미지를 만드는 데도 사용할 수 있습니다.

src/pages/index.astro
---
import { Picture } from 'astro:assets';
import myImage from "../assets/my_image.png"; // 1600x900의 이미지
---
<!-- Picture 컴포넌트에서는 'alt'가 필수입니다. -->
<Picture src={myImage} formats={['avif', 'webp']} alt="A description of my image." />
<!-- 결과 -->
<picture>
<source srcset="/_astro/my_image.hash.avif" type="image/avif" />
<source srcset="/_astro/my_image.hash.webp" type="image/webp" />
<img
src="/_astro/my_image.hash.png"
width="1600"
height="900"
decoding="async"
loading="lazy"
alt="A description of my image."
/>
</picture>

<Picture />반응형 이미지 속성을 포함하여 <Image /> 컴포넌트의 모든 속성과 다음을 허용합니다.

타입: ImageOutputFormat[]

<source> 태그에 사용할 이미지 형식의 배열입니다. 항목은 나열된 순서대로 <source> 요소로 추가되며, 이 순서에 따라 표시되는 형식이 결정됩니다. 최상의 성능을 얻으려면 가장 최신 형식 (예: webp 또는 avif)을 먼저 나열하세요. 기본적으로 ['webp']로 설정되어 있습니다.

타입: ImageOutputFormat

<img> 태그에 대한 대체 값으로 사용할 형식입니다. 정적 이미지의 기본값은 .png (또는 이미지가 JPG인 경우 .jpg), 애니메이션 이미지의 경우 .gif, SVG 파일의 경우 .svg입니다.

타입: HTMLAttributes<'picture'>

<picture> 태그에 추가될 속성의 객체입니다.

이 속성을 사용하여 외부 <picture> 요소 자체에 속성을 적용합니다. <Picture /> 컴포넌트에 직접 적용된 속성은 이미지 변환에 사용되는 속성을 제외하고 내부 <img> 요소에 적용됩니다.

src/components/MyComponent.astro
---
import { Picture } from "astro:assets";
import myImage from "../my_image.png"; // 1600x900의 이미지
---
<Picture
src={myImage}
alt="A description of my image."
pictureAttributes={{ style: "background-color: red;" }}
/>
<!-- 결과 -->
<picture style="background-color: red;">
<source srcset="/_astro/my_image.hash.webp" type="image/webp" />
<img
src="/_astro/my_image.hash.png"
alt="A description of my image."
width="1600"
height="900"
loading="lazy"
decoding="async"
/>
</picture>

<Image /> 또는 <Picture /> 컴포넌트에 layout 속성을 설정하면 반응형 이미지가 생성되고 추가 속성을 설정할 수 있게 됩니다.

src/components/MyComponent.astro
---
import { Image } from 'astro:assets';
import myImage from '../assets/my_image.png';
---
<Image src={myImage} alt="A description of my image." layout='constrained' width={800} height={600} />

레이아웃이 설정되면 이미지의 크기와 레이아웃 유형에 따라 srcsetsizes 속성이 자동으로 생성됩니다. 이전 <Image /> 컴포넌트는 다음과 같은 HTML 출력을 생성합니다.

<img
src="/_astro/my_image.hash3.webp"
srcset="/_astro/my_image.hash1.webp 640w,
/_astro/my_image.hash2.webp 750w,
/_astro/my_image.hash3.webp 800w,
/_astro/my_image.hash4.webp 828w,
/_astro/my_image.hash5.webp 1080w,
/_astro/my_image.hash6.webp 1280w,
/_astro/my_image.hash7.webp 1600w"
alt="A description of my image"
sizes="(min-width: 800px) 800px, 100vw"
loading="lazy"
decoding="async"
fetchpriority="auto"
width="800"
height="600"
style="--fit: cover; --pos: center;"
data-astro-image="constrained"
>

layout의 값은 컨테이너에 따라 이미지 크기를 조정하는 방법을 결정하기 위해 <img> 태그에 적용되는 기본 스타일도 정의합니다.

Responsive Image Styles
:where([data-astro-image]) {
object-fit: var(--fit);
object-position: var(--pos);
}
:where([data-astro-image='full-width']) {
width: 100%;
}
:where([data-astro-image='constrained']) {
max-width: 100%;
}

<Image /> 또는 <Picture /> 컴포넌트에 fitposition props를 설정하여 기본 object-fitobject-position 스타일을 재정의할 수 있습니다.

타입: 'constrained' | 'full-width' | 'fixed' | 'none'
기본값: image.layout | 'none'

추가된 버전: astro@5.10.0

반응형 이미지를 정의하고 컨테이너 크기가 변경될 때 이미지의 크기를 조정하는 방법을 결정합니다. image.layout의 기본값을 재정의하는 데 사용할 수 있습니다.

  • constrained - 이미지가 컨테이너에 맞게 축소되어 가로 세로 비율을 유지하지만 지정된 widthheight 또는 이미지의 원래 크기를 초과하여 확대되지는 않습니다.

    이미지를 가능한 한 요청된 크기로 표시하되 작은 화면에 맞게 축소하려면 이 옵션을 사용합니다. 이는 Tailwind를 사용할 때 이미지의 기본 동작과 일치합니다. 잘 모르겠다면 이 레이아웃을 선택하는 것이 좋습니다.

  • full-width - 이미지가 가로 세로 비율을 유지하면서 컨테이너 너비에 맞게 크기가 조정됩니다.

    히어로 이미지 또는 페이지의 전체 너비를 차지해야 하는 이미지에 이 옵션을 사용합니다.

  • fixed - 이미지 크기가 조정되지 않고 요청된 크기를 유지합니다. 고밀도 디스플레이를 지원하기 위해 srcset을 생성하지만 다른 화면 크기에는 적용되지 않습니다.

    화면 너비보다 작은 아이콘이나 로고, 고정 너비 컨테이너의 이미지 등 이미지 크기가 조정되지 않는 경우에 이 옵션을 사용합니다.

  • none - 이미지가 반응형으로 작동하지 않습니다. srcset 또는 sizes가 자동으로 생성되지 않으며 스타일이 적용되지 않습니다.

    기본 레이아웃을 사용하도록 설정했지만 특정 이미지에 대해 사용하지 않으려는 경우에 유용합니다.

예를 들어, 기본 레이아웃으로 constrained를 설정하면 개별 이미지의 layout 속성을 재정의할 수 있습니다:

src/components/MyComponent.astro
---
import { Image } from 'astro:assets';
import myImage from '../assets/my_image.png';
---
<Image src={myImage} alt="This will use constrained layout" width={800} height={600} />
<Image src={myImage} alt="This will use full-width layout" layout="full-width" />
<Image src={myImage} alt="This will disable responsive images" layout="none" />

타입: 'contain' | 'cover' | 'fill' | 'none' | 'scale-down'
기본값: image.objectFit | 'cover'

추가된 버전: astro@5.10.0

layout 속성이 설정되거나 구성된 경우 활성화됩니다. 가로 세로 비율이 변경된 경우 반응형 이미지를 자르는 방법을 정의합니다.

값은 CSS object-fit의 값과 일치합니다. 기본값은 cover이지만, image.objectFit이 설정된 경우 이 속성의 값이 기본값입니다. 기본 object-fit 스타일을 재정의하는 데 사용할 수 있습니다.

타입: string
기본값: image.objectPosition | 'center'

추가된 버전: astro@5.10.0

layout 속성이 설정 또는 구성된 경우 활성화됩니다. 가로 세로 비율이 변경된 경우 반응형 이미지를 자르는 위치를 정의합니다.

값은 CSS object-position의 값과 일치합니다. 기본값은 center이지만, image.objectPosition이 설정된 경우 이 속성의 값이 기본값입니다. 기본 object-position 스타일을 재정의하는 데 사용할 수 있습니다.

타입: (options: UnresolvedImageTransform) => Promise<GetImageResult>

getImage() 함수는 HTML이 아닌 다른 곳 (예: API 경로)에서 사용할 이미지를 생성하기 위한 것입니다. 또한 사용자 정의 <Image /> 컴포넌트를 만들 수도 있습니다.

이 함수는 Image 컴포넌트와 동일한 속성을 가진 (alt 제외) 옵션 객체를 사용하며, GetImageResult 객체를 반환합니다.

다음 예시는 <div />에 AVIF background-image를 생성합니다.

src/components/Background.astro
---
import { getImage } from "astro:assets";
import myBackground from "../background.png"
const optimizedBackground = await getImage({src: myBackground, format: 'avif'})
---
<div style={`background-image: url(${optimizedBackground.src});`}><slot /></div>

타입: (url: string) => Promise<Omit<ImageMetadata, ‘src’ | ‘fsPath’>>

추가된 버전: astro@4.12.0

원격 이미지의 원래 widthheight를 자동으로 설정하는 함수입니다. 이 함수는 inferSize 속성을 전달하는 대신 사용할 수 있습니다.

import { inferRemoteSize } from 'astro:assets';
const { width, height } = await inferRemoteSize("https://example.com/cat.png");

타입: () => Promise<ImageService>

추가된 버전: astro@2.1.3

확인된 이미지 서비스를 검색합니다.

타입: AstroConfig["image"]

추가된 버전: astro@3.0.9

사용자가 설정하여 모든 기본값과 병합된 이미지 구성 옵션입니다.

다음 타입은 가상 assets 모듈에서 가져옵니다.

import type {
LocalImageProps,
RemoteImageProps,
} from "astro/assets";

타입: ImageSharedProps<T> & { src: ImageMetadata | Promise<{ default: ImageMetadata; }> }

로컬 이미지의 속성을 설명합니다. 이는 src가 가져온 이미지의 형태와 일치하는지 확인합니다.

예시 사용법과 함께 src/의 가져온 이미지에 대해 알아보세요.

Types:

  • ImageSharedProps<T> & { src: string; inferSize: true; }
  • ImageSharedProps<T> & { src: string; inferSize?: false | undefined; }

원격 이미지의 속성을 설명합니다. 이는 inferSize가 제공되지 않거나 false로 설정된 경우 widthheight가 모두 필수임을 보장합니다.

다음 도우미는 일반 assets 모듈에서 가져옵니다.

import {
baseService,
getConfiguredImageService,
getImage,
isLocalService,
} from "astro/assets";

타입: Omit<LocalImageService, ‘transform’>

내장된 로컬 이미지 서비스이며, 이를 확장하여 사용자 정의 이미지 서비스를 만들 수 있습니다.

다음 예시는 baseService를 재사용하여 새 이미지 서비스를 생성합니다.

src/image-service.ts
import { baseService } from "astro/assets";
const newImageService = {
getURL: baseService.getURL,
parseURL: baseService.parseURL,
getHTMLAttributes: baseService.getHTMLAttributes,
async transform(inputBuffer, transformOptions) {...}
}

See getConfiguredImageService() from astro:assets.

타입: (options: UnresolvedImageTransform, imageConfig: AstroConfig[‘image’]) => Promise<GetImageResult>

astro:assetsgetImage()와 유사한 함수로, 두 개의 필수 인수(Image 컴포넌트와 동일한 속성을 가진 options 객체와 이미지 구성을 위한 객체)를 받습니다.

타입: (service: ImageService | undefined) => boolean

이미지 서비스의 유형을 확인하고 해당 서비스가 로컬 서비스일 경우 true를 반환합니다.

다음 타입들은 일반 assets 모듈에서 가져옵니다.

import type {
LocalImageProps,
RemoteImageProps,
} from "astro/assets";

astro:assetsLocalImageProps를 확인하세요.

astro:assetsRemoteImageProps를 확인하세요.

다음 도우미는 일반 assets 모듈의 utils 디렉터리에서 가져올 수 있으며, 이미지 서비스를 구축하기 위해 사용할 수 있습니다.

import {
isRemoteAllowed,
matchHostname,
matchPathname,
matchPattern,
matchPort,
matchProtocol,
isESMImportedImage,
isRemoteImage,
resolveSrc,
imageMetadata,
emitImageMetadata,
getOrigQueryParams,
inferRemoteSize,
propsToFilename,
hashTransform,
/* 다음 함수는 더 이상 사용되지 않습니다. */
emitESMImage,
} from "astro/assets/utils";

타입: (src: string, { domains, remotePatterns }: { domains: string[], remotePatterns: RemotePattern[] }) => boolean

추가된 버전: astro@4.0.0

제공된 도메인 및 원격 패턴을 기반으로, 소스 URL로 식별되는 지정된 원격 리소스가 허용되는지 여부를 결정합니다.

import { isRemoteAllowed } from 'astro/assets/utils';
const url = new URL('https://example.com/images/test.jpg');
const domains = ['example.com', 'anotherdomain.com'];
const remotePatterns = [
{
protocol: 'https',
hostname: 'images.example.com',
pathname: '/**', // 이 호스트 이름 아래의 모든 경로를 허용합니다.
}
];
isRemoteAllowed(url.href, { domains, remotePatterns }); // 출력: `true`

타입: (url: URL, hostname?: string, allowWildcard = false) => boolean

추가된 버전: astro@4.0.0

주어진 URL의 호스트 이름이 지정된 호스트 이름과 일치하는지 확인하며, 선택적으로 와일드카드 패턴을 지원합니다.

import { matchHostname } from 'astro/assets/utils';
const url = new URL('https://sub.example.com/path/to/resource');
matchHostname(url, 'example.com'); // 출력: `false`
matchHostname(url, 'example.com', true); // 출력: `true`

타입: (url: URL, pathname?: string, allowWildcard = false) => boolean

추가된 버전: astro@4.0.0

주어진 URL의 경로 이름이 지정된 패턴과 일치하는지 확인하며, 선택적으로 와일드카드를 지원합니다.

import { matchPathname } from 'astro/assets/utils';
const testURL = new URL('https://example.com/images/photo.jpg');
matchPathname(testURL, '/images/photo.jpg'); // 출력: `true`
matchPathname(testURL, '/images/'); // 출력: `false`
matchPathname(testURL, '/images/*', true); // 출력: `true`

타입: (url: URL, remotePattern: RemotePattern) => boolean

추가된 버전: astro@4.0.0

주어진 URL이 프로토콜, 호스트 이름, 포트 및 경로 이름을 기반으로 지정된 원격 패턴과 일치하는지 평가합니다.

import { matchPattern } from 'astro/assets/utils';
const url = new URL('https://images.example.com/photos/test.jpg');
const remotePattern = {
protocol: 'https',
hostname: 'images.example.com',
pathname: '/photos/**', // /photos/ 아래 모든 파일들을 허용합니다.
};
matchPattern(url, remotePattern); // 출력: `true`

타입: (url: URL, port?: string) => boolean
기본값: true

추가된 버전: astro@4.0.0

주어진 URL의 포트가 지정된 포트와 일치하는지 확인합니다. 포트가 제공되지 않으면 true를 반환합니다.

import { matchPort } from 'astro/assets/utils';
const urlWithPort = new URL('https://example.com:8080/resource');
const urlWithoutPort = new URL('https://example.com/resource');
matchPort(urlWithPort, '8080'); // 출력: `true`
matchPort(urlWithoutPort, '8080'); // 출력: `false`

타입: (url: URL, protocol?: string) => boolean
기본값: true

추가된 버전: astro@4.0.0

제공된 URL의 프로토콜을 지정된 프로토콜과 비교합니다. 프로토콜이 일치하거나 프로토콜이 제공되지 않은 경우 true를 반환합니다.

import { matchProtocol } from 'astro/assets/utils';
const secureUrl = new URL('https://example.com/resource');
const regularUrl = new URL('http://example.com/resource');
matchProtocol(secureUrl, 'https'); // 출력: `true`
matchProtocol(regularUrl, 'https'); // 출력: `false`

타입: (src: ImageMetadata | string) => boolean

추가된 버전: astro@4.0.0

주어진 소스가 ECMAScript 모듈(ESM)로 가져온 이미지인지 판별합니다.

import { isESMImportedImage } from 'astro/assets/utils';
const imageMetadata = {
src: '/images/photo.jpg',
width: 800,
height: 600,
format: 'jpg',
};
const filePath = '/images/photo.jpg';
isESMImportedImage(imageMetadata); // 출력: `true`
isESMImportedImage(filePath); // 출력: `false`

타입: (src: ImageMetadata | string) => boolean

추가된 버전: astro@4.0.0

제공된 소스가 문자열 형태의 원격 이미지 URL인지 판별합니다.

import { isRemoteImage } from 'astro/assets/utils';
const imageUrl = 'https://example.com/images/photo.jpg';
const localImage = {
src: '/images/photo.jpg',
width: 800,
height: 600,
format: 'jpg',
};
isRemoteImage(imageUrl); // 출력: `true`
isRemoteImage(localImage); // 출력: `false`

타입: (src: UnresolvedImageTransform[‘src’]) => Promise<string | ImageMetadata>

추가된 버전: astro@4.0.0

이미지 소스를 반환합니다. 이 함수는 src가 Promise (예: 동적 import())인 경우, 이를 await하여 올바른 src 값을 추출합니다. src가 이미 해석된 값이면 그대로 반환합니다.

import { resolveSrc } from 'astro/assets/utils';
import localImage from "./images/photo.jpg";
const resolvedLocal = await resolveSrc(localImage);
// 예시 값: `{ src: '/@fs/home/username/dev/astro-project/src/images/photo.jpg', width: 800, height: 600, format: 'jpg' }`
const resolvedRemote = await resolveSrc("https://example.com/remote-img.jpg");
// 값: `"https://example.com/remote-img.jpg"`
const resolvedDynamic = await resolveSrc(import("./images/dynamic-image.jpg"))
// 예시 값: `{ src: '/@fs/home/username/dev/astro-project/src/images/dynamic-image.jpg', width: 800, height: 600, format: 'jpg' }`

타입: (data: Uint8Array, src?: string) => Promise<Omit<ImageMetadata, ‘src’ | ‘fsPath’>>

추가된 버전: astro@4.0.0

제공된 이미지 데이터에서 크기, 형식, 방향과 같은 이미지 메타데이터를 추출합니다.

import { imageMetadata } from 'astro/assets/utils';
const binaryImage = new Uint8Array([/* ...바이너리 이미지 데이터... */]);
const sourcePath = '/images/photo.jpg';
const metadata = await imageMetadata(binaryImage, sourcePath);
// 예시 값:
// {
// width: 800,
// height: 600,
// format: 'jpg',
// orientation: undefined
// }

타입: (id: string | undefined, fileEmitter?: Rollup.EmitFile) => Promise<(ImageMetadata & { contents?: Buffer }) | undefined>

추가된 버전: astro@5.7.0

이미지 파일을 처리하여 메타데이터를 내보내고 선택적으로 콘텐츠를 내보냅니다. 빌드 모드에서는 fileEmitter를 사용하여 자산 참조를 생성합니다. 개발 모드에서는 메타데이터를 위한 쿼리 매개변수가 있는 로컬 파일 URL로 해석됩니다.

import { emitImageMetadata } from 'astro/assets/utils';
const imageId = '/images/photo.jpg';
const metadata = await emitImageMetadata(imageId);
// 예시 값:
// {
// src: '/@fs/home/username/dev/astro-project/src/images/photo.jpg?origWidth=800&origHeight=600&origFormat=jpg',
// width: 800,
// height: 600,
// format: 'jpg',
// contents: Uint8Array([...])
// }

타입: (params: URLSearchParams) => Pick<ImageMetadata, ‘width’ | ‘height’ | ‘format’> | undefined

추가된 버전: astro@4.0.0

URLSearchParams 객체에서 이미지의 width, heightformat을 검색합니다. 이러한 매개변수가 누락되었거나 유효하지 않으면 함수는 undefined를 반환합니다.

import { getOrigQueryParams } from 'astro/assets/utils';
const url = new URL('https://example.com/image.jpg?width=800&height=600&format=jpg');
const origParams = getOrigQueryParams(url.searchParams);
// 예시 값:
// {
// width: 800,
// height: 600,
// format: 'jpg'
// }

타입: (url: string) => Promise<Omit<ImageMetadata, ‘src’ | ‘fsPath’>>

추가된 버전: astro@4.0.0

데이터를 스트리밍하고 충분한 메타데이터를 사용할 수 있을 때까지 점진적으로 분석하여 원격 이미지의 크기를 추론합니다.

import { inferRemoteSize } from 'astro/assets/utils';
const remoteImageUrl = 'https://example.com/image.jpg';
const imageSize = await inferRemoteSize(remoteImageUrl);
// 예시 값:
// {
// width: 1920,
// height: 1080,
// format: 'jpg'
// }

타입: (filePath: string, transform: ImageTransform, hash: string) => string

추가된 버전: astro@4.0.0

소스 경로, 변환 속성 및 고유한 해시를 기반으로 이미지의 포맷팅된 파일 이름을 생성합니다.

포맷팅된 파일 이름은 다음 구조를 따릅니다.

<prefixDirname>/<baseFilename>_<hash><outputExtension>

  • prefixDirname: 이미지가 ESM으로 가져온 이미지인 경우, 원본 파일 경로의 디렉토리 이름입니다. 그렇지 않으면 빈 문자열입니다.
  • baseFilename: 파일이 data: URI인 경우 파일의 기본 이름 또는 해싱된 짧은 이름입니다.
  • hash: 변환된 파일을 구별하기 위해 생성된 고유한 해시 문자열입니다.
  • outputExtension: transform.format 또는 원본 파일 확장명에서 파생된 원하는 출력 파일 확장명입니다.
import { propsToFilename } from 'astro/assets/utils';
const filePath = '/images/photo.jpg';
const transform = { format: 'png', src: filePath };
const hash = 'abcd1234';
const filename = propsToFilename(filePath, transform, hash);
// 예시 값: '/images/photo_abcd1234.png'

타입: (transform: ImageTransform, imageService: string, propertiesToHash: string[]) => string

추가된 버전: astro@4.0.0

제공된 transform 객체를 선택한 속성 및 지정된 imageService를 기반으로 해시 문자열로 변환합니다.

import { hashTransform } from 'astro/assets/utils';
const transform = {
src: '/images/photo.jpg',
width: 800,
height: 600,
format: 'jpg',
};
const imageService = 'astro/assets/services/sharp';
const propertiesToHash = ['width', 'height', 'format'];
const hash = hashTransform(transform, imageService, propertiesToHash);
// 예시 값: 'd41d8cd98f00b204e9800998ecf8427e'

타입: (id: string | undefined, _watchMode: boolean, experimentalSvgEnabled: boolean, fileEmitter?: Rollup.EmitFile) => Promise<(ImageMetadata & { contents?: Buffer }) | undefined>

추가된 버전: astro@4.0.0

이미지 파일을 처리하여 메타데이터를 내보내고 선택적으로 콘텐츠를 내보냅니다. 빌드 모드에서는 fileEmitter를 사용하여 자산 참조를 생성합니다. 개발 모드에서는 메타데이터를 위한 쿼리 매개변수가 있는 로컬 파일 URL로 해석됩니다.

import { emitESMImage } from 'astro/assets/utils';
const imageId = '/images/photo.jpg';
const unusedWatchMode = false; // 더 이상 사용되지 않습니다.
const unusedExperimentalSvgEnabled = false; // SVG를 사용 중이고, 파일 데이터를 임베드하려는 경우에만 `true`로 설정합니다.
const image = await emitESMImage(imageId, unusedWatchMode, unusedExperimentalSvgEnabled);
// 예시 값:
// {
// src: '/@fs/home/username/dev/astro-project/src/images/photo.jpg?origWidth=800&origHeight=600&origFormat=jpg',
// width: 800,
// height: 600,
// format: 'jpg',
// contents: Uint8Array([...])
// }
import type {
GetImageResult,
ImageTransform,
UnresolvedImageTransform,
ImageMetadata,
ImageInputFormat,
ImageOutputFormat,
ImageQuality,
ImageQualityPreset,
RemotePattern,
ImageService,
ExternalImageService,
LocalImageService,
ImageServiceConfig,
} from "astro";

타입: object

추가된 버전: astro@2.2.0

getImage() 호출 후 변환된 결과에 대해 설명합니다.

타입: Record<string, any>

이미지를 렌더링하기 위해 필요한 추가 HTML 속성을 정의합니다. (예: 너비, 높이, 스타일)

타입: ImageTransform

검증 후 변환 설정을 설명합니다.

타입: ImageTransform

원본 변환 설정을 설명합니다.

타입: string

생성된 이미지의 경로입니다.

타입: { values: { transform: ImageTransform; descriptor?: string; attributes?: Record<string, any>; url: string; }[]; attribute: string; }

추가된 버전: astro@3.3.0

srcset 속성을 렌더링하는 방법을 설명하는 객체입니다.

타입: { transform: ImageTransform; descriptor?: string; attributes?: Record<string, any>; url: string; }[]

생성된 값(각 항목에는 URL과 크기 설명자가 포함되어 있음)의 배열입니다. 이는 srcset 속성 값을 수동으로 생성하는 데 사용할 수 있습니다.

타입: string

srcset 속성에 사용할 수 있는 값입니다.

타입: object

이미지 변환 서비스에서 허용하는 옵션을 정의합니다. 여기에는 필수 src 속성, 선택적 사전 정의된 속성, 이미지 서비스에서 필요한 추가 속성이 포함됩니다.

타입: ImageMetadata | string

public 디렉터리에 있는 로컬 이미지의 경로, 원격 이미지의 URL 또는 가져온 이미지의 데이터를 정의합니다.

타입: number | undefined

이미지의 너비입니다.

타입: number | undefined

이미지의 높이입니다.

타입: number[] | undefined

추가된 버전: astro@3.3.0

이미지에 대해 생성할 너비 목록입니다.

타입: (number | `${number}x`)[] | undefined

추가된 버전: astro@3.3.0

이미지에 대해 생성할 픽셀 밀도 목록입니다.

타입: ImageQuality | undefined

출력 이미지에 대해 원하는 품질입니다.

타입: ImageOutputFormat | undefined

출력 이미지에 대해 원하는 형식입니다.

타입: 'fill' | 'contain' | 'cover' | 'none' | 'scale-down' | string | undefined

추가된 버전: astro@5.0.0

object-fit CSS 속성에 허용되는 값 목록을 정의하며, 어떤 문자열로든 확장 가능합니다.

타입: string | undefined

추가된 버전: astro@5.0.0

object-position CSS 속성의 값을 제어합니다.

타입: Omit<ImageTransform, “src”> & { src: ImageMetadata | string | Promise<{ default: ImageMetadata }>; inferSize?: boolean; }

변환 옵션을 가진 이미지를 나타냅니다. ImageTransform 타입과 동일한 속성들을 포함하지만, src 타입이 다르며 inferSize라는 추가 속성을 가집니다.

타입: ImageMetadata | string | Promise<{ default: ImageMetadata }>

가져오거나 public 디렉터리에 위치한 이미지의 경로입니다. 또는 원격 이미지의 URL입니다.

타입: boolean

이미지의 너비와 높이를 추론해야 하는지 여부를 결정합니다.

<Image />에서 사용할 수 있는 inferSize 속성도 확인하세요.

타입: { src: string; width: number; height: number; format: ImageInputFormat; orientation?: number; }

추가된 버전: astro@2.1.3

이미지 가져오기 중에 수집된 데이터를 설명합니다. 다음 속성을 포함합니다.

타입: string

파일 시스템 상의 이미지의 절대 경로입니다.

타입: number

이미지의 너비입니다.

타입: number

이미지의 높이입니다.

타입: ImageInputFormat

이미지의 형식입니다.

타입: number

추가된 버전: astro@2.8.3

이미지 메타데이터에 이 정보가 포함된 경우, 이미지의 방향입니다.

타입: "jpeg" | "jpg" | "png" | "tiff" | "webp" | "gif" | "svg" | "avif"

추가된 버전: astro@2.2.0

가져온 이미지에 대해 지원되는 형식의 유니온을 설명합니다.

타입: string | "jpeg" | "jpg" | "png" | "webp" | "svg" | "avif"

추가된 버전: astro@2.2.0

출력 이미지의 형식을 지정합니다. 이는 미리 정의된 리터럴이나 임의의 문자열일 수 있습니다.

타입: ImageQualityPreset | number

추가된 버전: astro@2.2.0

출력 이미지의 지각적 품질을 사전 정의된 리터럴의 합집합, 문자열 또는 숫자로 표현합니다.

타입: string | "low" | "mid" | "high" | "max"

추가된 버전: astro@2.2.0

이미지 품질을 제어하기 위해 사용 가능한 사전 설정을 정의하며, 어떤 문자열로도 확장 가능합니다.

타입: { hostname?: string; pathname?: string; protocol?: string; port?: string; }

추가된 버전: astro@5.14.2

원격 호스트를 네 가지 선택적 속성(hostname, pathname, protocol, port)을 통해 설명합니다.

타입: ExternalImageService | LocalImageService

로컬 또는 외부 이미지 서비스가 제공해야 하는 훅을 정의합니다.

타입: object

외부 이미지 변환 서비스가 제공해야 하는 훅을 정의합니다. getUrl()이 필수이며, 추가로 세 가지 훅을 지원합니다.

이미지 서비스 API 참조 문서에서 사용법 예시를 통해 외부 서비스 구축 방법을 알아보세요.

타입: object

로컬 이미지 변환 서비스가 제공해야 하는 훅을 정의합니다. 이는 getUrl(), parseUrl(), transform() 훅을 요구하며, 추가 훅을 지원합니다.

이미지 서비스 API 참조 문서에서 사용법 예시를 통해 로컬 서비스 구축 방법을 알아보세요.

타입: { entrypoint: 'astro/assets/services/sharp' | string; config?: T; }

추가된 버전: astro@2.3.3

이미지 서비스의 구성 객체를 설명합니다. 다음 속성을 포함합니다.

타입: 'astro/assets/services/sharp' | string

이미지 서비스 모듈의 패키지 또는 경로입니다. Astro의 내장 Sharp 서비스 또는 타사 서비스일 수 있습니다.

타입: Record<string, any>

이미지 서비스에 전달되는 구성 객체입니다. 형태는 사용 중인 특정 서비스에 따라 달라집니다.

기여하기 커뮤니티 후원하기