Step 1: next/image 컴포넌트 가져오기 및 사용하기
next/image 컴포넌트를 사용하면 이미지를 최적화할 수 있습니다. 이 컴포넌트를 사용하려면 다음과 같이 코드를 작성합니다.
import Image from 'next/image';
const Post = ({ imageUrl }) => (
<div>
<Image
src={imageUrl}
alt="User uploaded image"
width={800} // 임시로 설정한 값
height={600} // 임시로 설정한 값
fill={true} // 이미지가 컨테이너를 채우도록 설정
/>
</div>
);
export default Post;
Step 2: next.config.js 파일에서 외부 호스트 구성
이미지를 외부 사이트(예: Cloudinary)에서 가져오려면, 해당 호스트를 next.config.js 파일에 구성해야 합니다. 다음과 같이 설정합니다.
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
domains: ['res.cloudinary.com'],
remotePatterns: [
{
protocol: 'https',
hostname: 'res.cloudinary.com',
pathname: '/**', // 모든 경로 허용
},
],
},
};
export default nextConfig;
이렇게 설정하면 res.cloudinary.com 도메인에서 이미지를 가져올 수 있습니다.
Step 3: 이미지의 원래 가로 세로 크기 설정
이미지의 원래 크기를 알 수 없는 경우에는 fill 속성을 사용할 수 있지만, 이 속성을 사용하면 이미지가 컨테이너를 꽉 채우게 됩니다. 사용자의 이미지를 최적화하려면 원본 이미지의 크기를 미리 알고 설정하는 것이 좋습니다. 만약 이미지 크기를 미리 알 수 없는 상황이라면, 사용자 업로드 후 서버에서 이미지 크기를 계산하여 전달하는 방법도 고려해볼 수 있습니다.
이미지 크기를 서버에서 계산하여 전달하는 예제:
- 서버에서 이미지 업로드 후 크기 계산:
const sharp = require('sharp');
const fs = require('fs');
const imagePath = 'path/to/uploaded/image.jpg';
sharp(imagePath)
.metadata()
.then(metadata => {
console.log(`Width: ${metadata.width}, Height: ${metadata.height}`);
// 이미지의 너비와 높이를 클라이언트로 전달
});
클라이언트에서 이미지의 너비와 높이 사용:
import Image from 'next/image';
const Post = ({ imageUrl, width, height }) => (
<div>
<Image
src={imageUrl}
alt="User uploaded image"
width={width}
height={height}
/>
</div>
);
export default Post;
이 방법을 사용하면, 이미지가 최적의 크기로 표시될 수 있습니다.
전체 코드 예제
다음을 참고하여 전체 코드를 작성해보겠습니다:
서버 코드 (예시)
서버에서 이미지를 업로드하고 크기를 계산하는 코드를 추가합니다.
const express = require('express');
const sharp = require('sharp');
const fs = require('fs');
const app = express();
app.post('/upload', (req, res) => {
// 이미지 업로드 처리
const imagePath = 'path/to/uploaded/image.jpg';
sharp(imagePath)
.metadata()
.then(metadata => {
res.json({
imageUrl: imagePath,
width: metadata.width,
height: metadata.height,
});
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
클라이언트 코드
이미지 URL과 크기를 받아서 이미지를 표시하는 컴포넌트:
import Image from 'next/image';
const Post = ({ imageUrl, width, height }) => (
<div>
<Image
src={imageUrl}
alt="User uploaded image"
width={width}
height={height}
/>
</div>
);
export default Post;
next.config.js 파일
외부 호스트를 허용하도록 설정합니다:
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
domains: ['res.cloudinary.com'],
remotePatterns: [
{
protocol: 'https',
hostname: 'res.cloudinary.com',
pathname: '/**',
},
],
},
};
export default nextConfig;














댓글 ( 0)
댓글 남기기