首先需要npm安装 react-avatar-editor 库(package.json中:"react-avatar-editor": "11.0.9")
//npm安装库
npm install --save react-avatar-editor
其次,获取所选的图像文件
selectImage = (e) => {
let ImageFile = e.target.files[0];
const { fileext } = getFileNameAndExt(ImageFile.name);
let IsGif = fileext.toLowerCase() === ".gif";
if (!isSupportedImgFile(fileext.toLowerCase()))
{
//非符合的文件
Modal.info({
title: '提示',
content: '图片格式错误,请重新选择!',
centered: true,
okText: '确定',
});
return;
}
//图像裁剪
//Gif不裁剪,裁剪就变为静态
//获取到的图像文件要转换成url才能展示
const fileReader = new FileReader();
fileReader.readAsDataURL(ImageFile );
fileReader.onload = (e) => {
const data= e.target.result;
this.setState(state => ({
...state,
imagesrc:data,
isGifHeadImage: IsGif ,
}));
}
}
注:
export const isSupportedImgFile = fileExt => {
return isFileExtInArray(['.jpg', '.jpeg', '.png', '.gif', '.bmp'], fileExt);
}
setEditorRef = editor => (this.editor = editor);
裁剪控件:
render() {
const { imagesrc, setEditorRef, isGifImage } = this.props;
const { scale } = this.state;
let style = {width:320, height: 320,cursor: 'move'};
return (
<div className="userhead" >
{
isGifImage ?
<img className="gifimage avatareditor" src={imagesrc} />
: <AvatarEditor
ref={setEditorRef}
image={imagesrc}
width={320}
height={320}
border={50}
borderRadius={0}
style={style}
className="avatareditor"
onWheel={this._onWheel}
scale={scale}
/>
}
</div>
);
}
_onWheel = (e) => {
var UpDown = e.nativeEvent.wheelDelta;
//大于0滚轮向上滚动,小于0滚轮向下滚动
//设定一步是10%
if(UpDown>0)
{
let Addta = this.state.scale + (UpDown / 120 /10);
this.setState(state => ({
...state,
scale:Addta
}));
}
else {
let delta = this.state.scale + (UpDown / 120 /10);
if (delta >= 1)
{
this.setState(state => ({
...state,
scale:delta
}));
}
else{
return;
}
}
}
注:改动borderRadius可将裁剪框改变
再讲裁剪得的文件上传即可。
onSubmitHead = (e) => {
var imageUrl;
if (this.state.isGifHeadImage)
{
imageUrl = this.state.imagesrc;
}
else
{
imageUrl = this.editor.getImage().toDataURL();
}
const hide = message.loading("图像正在上传", 0);
uploadImg(dataURLtoFile(imageUrl)).then(
// 进行http上传
(res) =>
{
hide();
if (res.data && res.data.state === "SUCCESS") {
// 上传成功,发送消息
const uploadResult = res.data;
xxxxxxxxx....;
}
else{
message.error("上传失败");
}
}
);
}