|
| 1 | +import { NextRequest, NextResponse } from 'next/server'; |
| 2 | +import sharp from 'sharp'; |
| 3 | + |
| 4 | +import fs from 'fs'; |
| 5 | +import path from 'path'; |
| 6 | + |
| 7 | +export async function GET(request: NextRequest) { |
| 8 | + const { searchParams } = new URL(request.url); |
| 9 | + |
| 10 | + const src = searchParams.get('src'); |
| 11 | + const width = searchParams.get('width'); |
| 12 | + const height = searchParams.get('height'); |
| 13 | + |
| 14 | + if (!src || typeof src !== 'string') { |
| 15 | + return new NextResponse('Missing or invalid "src" query parameter', { |
| 16 | + status: 400, |
| 17 | + }); |
| 18 | + } |
| 19 | + |
| 20 | + const widthInt = width ? parseInt(width as string, 10) : null; |
| 21 | + const heightInt = height ? parseInt(height as string, 10) : null; |
| 22 | + const isGif = src.endsWith('.gif'); |
| 23 | + |
| 24 | + const getImageBuffer = async () => { |
| 25 | + if (src.startsWith('http://') || src.startsWith('https://')) { |
| 26 | + // 외부 이미지 URL 처리 |
| 27 | + const response = await fetch(src, { |
| 28 | + next: { revalidate: 60 * 60 * 24 }, |
| 29 | + headers: { |
| 30 | + responseType: 'arraybuffer', |
| 31 | + }, |
| 32 | + }); |
| 33 | + const imageBuffer = await response.arrayBuffer(); |
| 34 | + |
| 35 | + return imageBuffer; |
| 36 | + } else { |
| 37 | + // 로컬 이미지 경로 처리 |
| 38 | + const imagePath = path.join('./public', src); |
| 39 | + const imageBuffer = fs.readFileSync(imagePath); |
| 40 | + |
| 41 | + return imageBuffer; |
| 42 | + } |
| 43 | + }; |
| 44 | + |
| 45 | + try { |
| 46 | + const imageBuffer = await getImageBuffer(); |
| 47 | + |
| 48 | + // 이미지 최적화 작업 |
| 49 | + const image = isGif |
| 50 | + ? sharp(imageBuffer, { animated: true }).gif() |
| 51 | + : sharp(imageBuffer).webp(); |
| 52 | + |
| 53 | + // 이미지 리사이징 |
| 54 | + if (widthInt || heightInt) { |
| 55 | + image.resize(widthInt, heightInt); |
| 56 | + } |
| 57 | + |
| 58 | + const optimizedImageBuffer = await image.toBuffer(); |
| 59 | + |
| 60 | + // 응답 헤더 설정 |
| 61 | + const contentTypeHeader = isGif |
| 62 | + ? { |
| 63 | + 'Content-Type': 'image/gif', |
| 64 | + } |
| 65 | + : { |
| 66 | + 'Content-Type': 'image/webp', |
| 67 | + }; |
| 68 | + |
| 69 | + // 최적화된 이미지 전송 |
| 70 | + return new NextResponse(optimizedImageBuffer, { |
| 71 | + status: 200, |
| 72 | + headers: contentTypeHeader, |
| 73 | + }); |
| 74 | + } catch (error) { |
| 75 | + console.error('Error optimizing image:', error); |
| 76 | + return new NextResponse('Error optimizing image', { |
| 77 | + status: 500, |
| 78 | + }); |
| 79 | + } |
| 80 | +} |
0 commit comments