이미지 처리
업로드 전에 클라이언트 측에서 이미지를 처리하여 대역폭 및 스토리지 비용을 절감하세요.
이미지 압축
import { useDropup } from '@samithahansaka/dropup';
import { compressImage } from '@samithahansaka/dropup/image';
function CompressedUploader() {
const { files, actions, getDropProps, getInputProps } = useDropup({
accept: 'image/*',
upload: { url: '/api/upload' },
// 업로드 전에 파일 처리
onFilesAdded: async (newFiles) => {
for (const file of newFiles) {
// 이미지 압축
const compressed = await compressImage(file.file, {
maxWidth: 1920,
maxHeight: 1080,
quality: 0.8,
});
// 압축된 버전으로 교체
actions.updateFileMeta(file.id, {
originalSize: file.size,
compressedFile: compressed,
});
}
},
});
return (
<div {...getDropProps()}>
<input {...getInputProps()} />
<p>Images will be compressed before upload</p>
</div>
);
}
압축 옵션
interface CompressOptions {
// 최대 크기 (가로세로 비율 유지)
maxWidth?: number; // 기본값: 1920
maxHeight?: number; // 기본값: 1080
// 품질 (0-1)
quality?: number; // 기본값: 0.8
// 출력 형식
type?: 'image/jpeg' | 'image/png' | 'image/webp'; // 기본값: 원본 타입
}
// 예제
await compressImage(file, { quality: 0.6 }); // 낮은 품질
await compressImage(file, { maxWidth: 800, maxHeight: 600 }); // 작은 크기
await compressImage(file, { type: 'image/webp' }); // WebP로 변환
압축과 함께 미리보기
import { useDropup } from '@samithahansaka/dropup';
import { compressImage } from '@samithahansaka/dropup/image';
import { useState } from 'react';
function PreviewWithCompression() {
const [compressionStats, setCompressionStats] = useState<Map<string, {
original: number;
compressed: number;
}>>(new Map());
const { files, actions, getDropProps, getInputProps } = useDropup({
accept: 'image/*',
onFilesAdded: async (newFiles) => {
for (const file of newFiles) {
const compressed = await compressImage(file.file, {
maxWidth: 1200,
quality: 0.75,
});
setCompressionStats(prev => new Map(prev).set(file.id, {
original: file.size,
compressed: compressed.size,
}));
// 업로드를 위해 압축된 파일 저장
actions.updateFileMeta(file.id, { compressedFile: compressed });
}
},
});
const formatSize = (bytes: number) => {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
};
return (
<div>
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Drop images to compress</p>
</div>
<div style={styles.grid}>
{files.map(file => {
const stats = compressionStats.get(file.id);
const savings = stats
? ((1 - stats.compressed / stats.original) * 100).toFixed(0)
: 0;
return (
<div key={file.id} style={styles.card}>
{file.preview && (
<img src={file.preview} alt="" style={styles.preview} />
)}
<p>{file.name}</p>
{stats && (
<p style={styles.stats}>
{formatSize(stats.original)} → {formatSize(stats.compressed)}
<span style={styles.savings}> (-{savings}%)</span>
</p>
)}
</div>
);
})}
</div>
</div>
);
}
const styles = {
dropzone: {
border: '2px dashed #ccc',
borderRadius: 8,
padding: 40,
textAlign: 'center' as const,
marginBottom: 20,
},
grid: {
display: 'grid',
gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))',
gap: 16,
},
card: {
border: '1px solid #eee',
borderRadius: 8,
padding: 12,
},
preview: {
width: '100%',
height: 150,
objectFit: 'cover' as const,
borderRadius: 4,
},
stats: {
fontSize: 12,
color: '#666',
},
savings: {
color: '#4caf50',
fontWeight: 'bold',
},
};
이미지 크기 조정
import { resizeImage } from '@samithahansaka/dropup/image';
// 정확한 크기로 조정
const resized = await resizeImage(file, {
width: 300,
height: 300,
mode: 'cover', // 'cover' | 'contain' | 'fill'
});
// 썸네일 생성
const thumbnail = await resizeImage(file, {
width: 150,
height: 150,
mode: 'cover',
});
크기 조정 모드
| 모드 | 설명 |
|---|---|
cover | 전체 영역을 채우며, 잘릴 수 있음 |
contain | 영역 내에 맞추며, 빈 공간이 있을 수 있음 |
fill | 채우기 위해 늘어나며 (왜곡될 수 있음) |
EXIF 방향 수정
일부 카메라는 EXIF 회전 데이터와 함께 이미지를 저장합니다. 표시 전에 방향을 수정하세요:
import { fixOrientation } from '@samithahansaka/dropup/image';
const corrected = await fixOrientation(file);
이미지 자르기
import { cropImage } from '@samithahansaka/dropup/image';
const cropped = await cropImage(file, {
x: 100, // 시작 X
y: 50, // 시작 Y
width: 400, // 자르기 너비
height: 400, // 자르기 높이
});
이미지 편집기 컴포넌트
import { useDropup } from '@samithahansaka/dropup';
import { compressImage, cropImage } from '@samithahansaka/dropup/image';
import { useState, useRef } from 'react';
function ImageEditor() {
const [selectedFile, setSelectedFile] = useState<DropupFile | null>(null);
const [cropArea, setCropArea] = useState({ x: 0, y: 0, width: 200, height: 200 });
const { files, actions, getDropProps, getInputProps } = useDropup({
accept: 'image/*',
maxFiles: 1,
multiple: false,
});
const handleCrop = async () => {
if (!selectedFile) return;
const cropped = await cropImage(selectedFile.file, cropArea);
// 원본을 자른 버전으로 교체
actions.updateFileMeta(selectedFile.id, {
processedFile: cropped,
});
};
const handleCompress = async () => {
if (!selectedFile) return;
const compressed = await compressImage(selectedFile.file, {
quality: 0.7,
});
actions.updateFileMeta(selectedFile.id, {
processedFile: compressed,
});
};
return (
<div style={styles.container}>
{files.length === 0 ? (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Drop an image to edit</p>
</div>
) : (
<div style={styles.editor}>
<div style={styles.preview}>
<img
src={files[0].preview}
alt=""
style={styles.image}
onClick={() => setSelectedFile(files[0])}
/>
</div>
<div style={styles.tools}>
<h4>Tools</h4>
<button onClick={handleCrop}>Crop</button>
<button onClick={handleCompress}>Compress</button>
<button onClick={() => actions.reset()}>Remove</button>
</div>
</div>
)}
</div>
);
}
const styles = {
container: {
maxWidth: 600,
margin: '0 auto',
},
dropzone: {
border: '2px dashed #ccc',
borderRadius: 8,
padding: 60,
textAlign: 'center' as const,
},
editor: {
display: 'flex',
gap: 20,
},
preview: {
flex: 1,
},
image: {
maxWidth: '100%',
borderRadius: 8,
},
tools: {
width: 150,
display: 'flex',
flexDirection: 'column' as const,
gap: 8,
},
};
이미지 형식 변환
import { convertImage } from '@samithahansaka/dropup/image';
// 더 작은 파일 크기를 위해 WebP로 변환
const webp = await convertImage(file, 'image/webp');
// JPEG로 변환
const jpeg = await convertImage(file, 'image/jpeg', { quality: 0.9 });
// PNG로 변환 (무손실)
const png = await convertImage(file, 'image/png');
이미지 메타데이터 가져오기
import { getImageMetadata } from '@samithahansaka/dropup/image';
const metadata = await getImageMetadata(file);
console.log(metadata);
// {
// width: 1920,
// height: 1080,
// aspectRatio: 1.78,
// orientation: 1, // EXIF 방향
// hasAlpha: false,
// format: 'image/jpeg',
// }
파이프라인 처리
여러 작업을 연결하세요:
import {
compressImage,
fixOrientation,
resizeImage,
} from '@samithahansaka/dropup/image';
async function processImage(file: File): Promise<File> {
let processed = file;
// 단계 1: 방향 수정
processed = await fixOrientation(processed);
// 단계 2: 너무 크면 크기 조정
const metadata = await getImageMetadata(processed);
if (metadata.width > 2000 || metadata.height > 2000) {
processed = await resizeImage(processed, {
maxWidth: 2000,
maxHeight: 2000,
});
}
// 단계 3: 압축
processed = await compressImage(processed, {
quality: 0.8,
type: 'image/webp',
});
return processed;
}
// 업로더에서 사용
const { files } = useDropup({
accept: 'image/*',
onFilesAdded: async (newFiles) => {
for (const file of newFiles) {
const processed = await processImage(file.file);
actions.updateFileMeta(file.id, { processedFile: processed });
}
},
});
브라우저 지원
이미지 처리는 Canvas API를 사용하며 모든 최신 브라우저에서 지원됩니다:
| 기능 | Chrome | Firefox | Safari | Edge |
|---|---|---|---|---|
| 크기 조정/자르기 | ✓ | ✓ | ✓ | ✓ |
| JPEG/PNG | ✓ | ✓ | ✓ | ✓ |
| WebP | ✓ | ✓ | 14+ | ✓ |
| EXIF 수정 | ✓ | ✓ | ✓ | ✓ |