跳转到主要内容

图像处理

在客户端处理图像后再上传,以减少带宽和存储成本。

图像压缩

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,在所有现代浏览器中均受支持:

功能ChromeFirefoxSafariEdge
调整大小/裁剪
JPEG/PNG
WebP14+
EXIF 修正