效果图
安装插件
npm i react-cropper
或者
yarn add react-cropper
主要代码
import React, { useRef, useState } from 'react';
import Cropper from 'react-cropper';
import 'cropperjs/dist/cropper.css';
import './index.less';
import { UploadOutlined } from '@ant-design/icons';
import { Upload, Button, Space, Divider } from 'antd';function cropper() {const cropperRef = useRef(null);const [imgsrc, setImgsrc] = useState(null); // 裁剪好的imgsrcconst [image, setImage] = useState("https://img2.baidu.com/it/u=1361506290,4036378790&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500"); // 记录图片const handleCrop = () => {const imageElement: any = cropperRef?.current;const cropper: any = imageElement?.cropper;const back64Cropper = cropper.getCroppedCanvas().toDataURL();console.log(cropper.getCroppedCanvas().toDataURL("image/jpeg"), "裁剪的base64编码");const base64Data = back64Cropper; // base64 格式的图像数据const url = base64ToUrl(base64Data); // 转换为 URLconsole.log("剪切url=", url); // 输出 URLsetImgsrc(url);};function base64ToUrl(base64Data: any) {const blob = base64ToBlob(base64Data); // 将 base64 转为 Blobconst url = URL.createObjectURL(blob); // 生成 URLreturn url;}function base64ToBlob(base64Data: any) {const byteString = atob(base64Data.split(',')[1]); // 将 base64 的数据部分解码成二进制数据const mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0]; // 获取 MIME 类型const ab = new ArrayBuffer(byteString.length);const ia = new Uint8Array(ab);for (let i = 0; i < byteString.length; i++) {ia[i] = byteString.charCodeAt(i);}return new Blob([ab], { type: mimeString }); // 生成 Blob 对象}const replaceImg = (img) => {console.log(img.file, "img");// 通过FileReader读取用户选取的文件const reader = new FileReader();reader.readAsDataURL(img.file.originFileObj);//加载图片后获取到图片的base64格式reader.onload = ({ target: { result } = {} }) => {console.log(result, "base64");//更新替换为目标图片setImage(result);};return false;};return (<div className='copy'><Cropperref={cropperRef}// 你所需要剪切图片的路径src={image}// 设置其他相关参数,例如裁剪框宽高比、裁剪框移动限制等style={{ height: 400, width: '100%' }}// 裁剪比例aspectRatio={16 / 9}/><div className='copy-but'><Space><Upload fileList={[]} onChange={replaceImg} accept="image/*"><Button size='large' className="upload" icon={<UploadOutlined />}>选择图片</Button></Upload><Button size='large' className="button" type="primary" onClick={handleCrop}>确定裁剪</Button></Space></div><div className='copy-img'><Divider plain>裁剪好的图片</Divider><div style={{ minHeight: "300px", minWidth: "500px", border: "1px solid #ccc", display: "flex", justifyContent: "center", alignItems: "center"}}><img src={imgsrc} alt="" /></div></div></div>)
}export default cropper