Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#654] 자체 이미지 최적화 작업 #656

Merged
merged 18 commits into from
Jul 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
"react-dom": "18.2.0",
"react-error-boundary": "^3.1.4",
"react-hook-form": "^7.43.2",
"react-intersection-observer": "^9.4.3"
"react-intersection-observer": "^9.4.3",
"sharp": "^0.32.6"
},
"devDependencies": {
"@babel/core": "^7.22.8",
Expand Down
80 changes: 80 additions & 0 deletions src/app/api/imageOptimize/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { NextRequest, NextResponse } from 'next/server';
import sharp from 'sharp';

import fs from 'fs';
import path from 'path';

export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);

const src = searchParams.get('src');
const width = searchParams.get('width');
const height = searchParams.get('height');

if (!src || typeof src !== 'string') {
return new NextResponse('Missing or invalid "src" query parameter', {
status: 400,
});
}

const widthInt = width ? parseInt(width as string, 10) : null;
const heightInt = height ? parseInt(height as string, 10) : null;
const isGif = src.endsWith('.gif');

const getImageBuffer = async () => {
if (src.startsWith('http://') || src.startsWith('https://')) {
// 외부 이미지 URL 처리
const response = await fetch(src, {
next: { revalidate: 60 * 60 * 24 },
headers: {
responseType: 'arraybuffer',
},
});
const imageBuffer = await response.arrayBuffer();

return imageBuffer;
} else {
// 로컬 이미지 경로 처리
const imagePath = path.join('./public', src);
const imageBuffer = fs.readFileSync(imagePath);

return imageBuffer;
}
};

try {
const imageBuffer = await getImageBuffer();

// 이미지 최적화 작업
const image = isGif
? sharp(imageBuffer, { animated: true }).gif()
: sharp(imageBuffer).webp();

// 이미지 리사이징
if (widthInt || heightInt) {
image.resize(widthInt, heightInt);
}

const optimizedImageBuffer = await image.toBuffer();

// 응답 헤더 설정
const contentTypeHeader = isGif
? {
'Content-Type': 'image/gif',
}
: {
'Content-Type': 'image/webp',
};

// 최적화된 이미지 전송
return new NextResponse(optimizedImageBuffer, {
status: 200,
headers: contentTypeHeader,
});
} catch (error) {
console.error('Error optimizing image:', error);
return new NextResponse('Error optimizing image', {
status: 500,
});
}
}
5 changes: 3 additions & 2 deletions src/app/global-error.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
'use client';

import Button from '@/components/common/Button';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import Image from 'next/image';

import Button from '@/components/common/Button';

export const ErrorPage = () => {
const router = useRouter();
Expand Down
5 changes: 3 additions & 2 deletions src/app/group/[groupId]/not-found.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Button from '@/components/common/Button';
import Image from 'next/image';
import Link from 'next/link';
import Image from 'next/image';

import Button from '@/components/common/Button';

export default function NotFound() {
return (
Expand Down
2 changes: 1 addition & 1 deletion src/app/login/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use client';

import Image from 'next/image';
import Link from 'next/link';
import Image from 'next/image';

import { IconKakao } from '@public/icons';
import { KAKAO_LOGIN_URL } from '@/constants';
Expand Down
5 changes: 3 additions & 2 deletions src/app/not-found.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
'use client';

import Button from '@/components/common/Button';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import Image from 'next/image';

import Button from '@/components/common/Button';

const NotFound = () => {
const router = useRouter();
Expand Down
7 changes: 4 additions & 3 deletions src/components/book/BookCover.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
'use client';

import { ComponentPropsWithoutRef, useState } from 'react';
import Image from 'next/image';

import { DATA_URL } from '@/constants';

import Image from '@/components/common/Image';

type BookCoverSize =
| 'xsmall'
| 'small'
Expand Down Expand Up @@ -78,7 +80,6 @@ const BookCover = ({ src, title, size = 'medium' }: BookCoverProps) => {
>
{src && !isError ? (
<Image
unoptimized
src={src}
alt={title || 'book-cover'}
placeholder="blur"
Expand All @@ -89,7 +90,7 @@ const BookCover = ({ src, title, size = 'medium' }: BookCoverProps) => {
/>
) : (
/** default cover line */
<div className="absolute left-[5%] h-full w-[0.3rem] bg-black-400"></div>
<div className="absolute left-[5%] h-full w-[0.3rem] bg-black-400" />
)}
</div>
);
Expand Down
2 changes: 1 addition & 1 deletion src/components/bookShelf/BookShelf.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ const Book = ({
src={imageUrl}
alt={title}
onLoadingComplete={handleOnLoadImage}
className=" rounded-[1px] object-cover"
className="rounded-[1px] object-cover"
sizes="9.1rem"
fill
style={{ visibility: bookSpineColor ? 'visible' : 'hidden' }}
Expand Down
2 changes: 1 addition & 1 deletion src/components/common/Avatar.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use client';

import { Children, ReactNode, useState } from 'react';
import Image from 'next/image';
import { Children, ReactNode, useState } from 'react';

type AvatarSize = 'small' | 'medium' | 'large';
interface AvatarProps {
Expand Down
48 changes: 48 additions & 0 deletions src/components/common/Image.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import NextImage from 'next/image';
import type { ComponentPropsWithRef } from 'react';

type ImageProps = Omit<ComponentPropsWithRef<typeof NextImage>, 'src'> & {
src: string;
};

const Image = ({
src,
alt,
width,
height,
fill = false,
sizes,
className,
priority = false,
loading = 'lazy',
placeholder = 'empty',
blurDataURL,
...props
}: ImageProps) => {
const params = new URLSearchParams({ src });

if (width) params.append('width', width.toString());
if (height) params.append('height', height.toString());

const optimizedSrc = `/api/imageOptimize?${params.toString()}`;

return (
<NextImage
unoptimized
src={optimizedSrc}
alt={alt}
width={width}
height={height}
fill={fill}
sizes={sizes}
priority={priority}
loading={loading}
placeholder={placeholder}
blurDataURL={blurDataURL}
className={className}
{...props}
/>
);
};

export default Image;
1 change: 0 additions & 1 deletion src/components/common/PWAServiceWorkerProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ const PWAServiceWorkerProvider = ({

try {
registerWorker();
console.log('register success!');
} catch (error) {
console.error('register failed: ', error);
}
Expand Down
Loading
Loading