画像処理
アップロード前にクライアントサイドで画像を処理し、帯域幅とストレージコストを削減します。
画像圧縮
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>画像はアップロード前に圧縮されます</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>画像をドロップして圧縮</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>編集する画像をドロップ</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>ツール</h4>
<button onClick={handleCrop}>クロップ</button>
<button onClick={handleCompress}>圧縮</button>
<button onClick={() => actions.reset()}>削除</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修正 | ✓ | ✓ | ✓ | ✓ |