NextJS - 블러 효과로 이미지 로드하기
작성 일자 : 2024년 09월 01일
1. 개요
프론트엔드에서 사용자 경험을 개선하는 방법 중 하나는 이미지가 로드되는 동안 블러 플레이스홀더를 사용하는 것입니다.
이번 블로그 포스트에서는 Next.js 애플리케이션에서 블러 효과를 사용하여 원격 이미지 로딩을 구현하는 방법을 살펴봅니다.
예시
2. 준비 작업
구현을 시작하기 전에 다음 사항이 필요합니다.
npx create-next-app
을 통해서 NextJS 프로젝트를 생성합니다.- 이미지 프로세싱을 위해서
sharp
패키지를 설치합니다.npm install sharp
명령어를 통해 설치할 수 있습니다.
3. 이미지를 불러오고 블러 효과 적용하기
먼저 원격 이미지를 가져와 처리할 유틸리티 함수가 필요합니다.
images.ts
유틸 파일에서, sharp
라이브러리를 사용하여 이미지 크기를 조정하고 블러 효과를 위해 base64 문자열로 변환하겠습니다.
images.ts
파일을 생성합니다.- 다음 코드를 추가합니다.
import sharp from "sharp";
function bufferToBase64(buffer: Buffer): string {
return `data:image/png;base64,${buffer.toString("base64")}`;
}
async function getFileBufferRemote(url: string) {
const response = await fetch(url);
return Buffer.from(await response.arrayBuffer());
}
export async function getPlaceholderImage(url: string | null) {
if (!url) return null;
try {
const originalBuffer = await getFileBufferRemote(url);
const resizedBuffer = await sharp(originalBuffer).resize(20).toBuffer();
return bufferToBase64(resizedBuffer);
} catch {
return null;
}
}
- URL을 가져와서 이미지를 fetch 한 다음 더 작은 크기(너비 20px)로 크기를 조정하고 base64 문자열로 변환하는 함수
getPlaceholderImage
를 정의하였습니다.
4. 이미지 컴포넌트 생성하기
다음으로, 이미지 컴포넌트를 생성하고 블러 효과를 적용합니다.
components/Image.tsx
파일을 생성합니다.- 다음 코드를 추가합니다.
import Image from "next/image";
import { getPlaceholderImage } from "@/lib/images";
interface BlurImageProps {
src: string;
alt: string;
width: number;
height: number;
}
export default async function BlurImage({ src, alt, width, height }: BlurImageProps) {
const placeholderImage = await getPlaceholderImage(src);
return (
<Image
src={src}
alt={alt}
width={width}
height={height}
layout="responsive"
objectFit="cover"
placeholder={placeholderImage ? "blur" : "empty"}
blurDataURL={placeholderImage ?? undefined}
/>
);
}
- 이 컴포넌트에서는 next/image 컴포넌트를 사용하여 이미지 로딩을 처리합니다.
- 블러 효과를 얻기 위해 base64 문자열을 blurDataURL 프로퍼티로 전달합니다.