生成一个 image splitter 组件,用户上传一张照片,选择行、列数量,点击按钮,就会自动分割,并打包成 zip 格式自动下载。
就会生成一个功能完整的组件:
'use client'
import React, { useState } from 'react';
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
const ImageSplitter = () => {
const [image, setImage] = useState(null);
const [rows, setRows] = useState(3);
const [cols, setCols] = useState(3);
const handleImageUpload = (e: React.ChangeEvent) => {
if (e.target.files && e.target.files[0]) {
setImage(e.target.files[0]);
}
};
const handleSplitImage = async () => {
if (!image) return;
const img = new Image();
img.src = URL.createObjectURL(image);
img.onload = async () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return;
const zip = new JSZip();
const { width, height } = img;
const pieceWidth = width / cols;
const pieceHeight = height / rows;
for (let r = 0; r
Upload an image:
Enter number of rows:
setRows(parseInt(e.target.value))}
min="1"
className="mb-4 w-full p-2 border border-gray-300 rounded"
/>
Enter number of columns:
setCols(parseInt(e.target.value))}
min="1"
className="mb-4 w-full p-2 border border-gray-300 rounded"
/>
Split Image
);
};
export default ImageSplitter;
当然一开始样式有点丑,我补充了一句:使用 tailwind 优化一下样式,要现代感,柔色调
大体效果就出来了:
https://imagesplitter.org/