在项目中我们常常会遇到对上传的图片进行裁剪后上传,比如:报名一些活动时需要对自己的头像照片进行裁剪;一些设计网站用户为了展示可以对图片进行旋转等等会有一些对图片进行处理
一,首先,需要下载插件npm i vue-cropper --save
或者使用cnpm
二,然后在组件内引入
import { VueCropper } from "vue-cropper";
export default {
components: { VueCropper },
}
三,最后使用
<!-- 图片剪裁以及预览 -->
<a-row>
<a-col :span="24" :style="{ height: '100px', width: '100px' }">
<vue-cropper
ref="cropper"
:img="options.headImgUrl"
:info="true"
:autoCrop="options.autoCrop"
:autoCropWidth="options.autoCropWidth"
:autoCropHeight="options.autoCropHeight"
:fixedBox="options.fixedBox"
@realTime="realTime"
outputType="png"
/>
<div class="avatar-upload-preview">
<img :src="previews.url" :style="previews.img" />
</div>
</a-col>
</a-row>
<br />
<!-- 上传,上下左右旋转以及放大缩小 -->
<a-row>
<a-col :lg="2" :md="2">
<a-upload
action="#"
:http-request="requestUpload"
:showUploadList="false"
:before-upload="beforeUpload"
accept="image/*"
>
<a-button>选择<a-icon type="upload" /></a-button>
</a-upload>
</a-col>
<a-col :lg="{ span: 1, offset: 7 }" :md="2">
<a-button icon="plus" @click="changeScale(1)"></a-button>
</a-col>
<a-col :lg="{ span: 1, offset: 3 }" :md="2">
<a-button icon="minus" @click="changeScale(-1)"></a-button>
</a-col>
<a-col :lg="{ span: 1, offset: 3 }" :md="2">
<a-button icon="undo" @click="rotateLeft()"></a-button>
</a-col>
<a-col :lg="{ span: 1, offset: 3 }" :md="2">
<a-button icon="redo" @click="rotateRight()"></a-button>
</a-col>
</a-row>
data() {
return {
//图片裁剪
options: {
headImgUrl: "", //裁剪图片的地址
autoCrop: true, // 是否默认生成截图框
autoCropWidth: 64, // 默认生成截图框宽度
autoCropHeight: 64, // 默认生成截图框高度
fixedBox: true, // 固定截图框大小 不允许改变
},
//图片预览
previews: {},
file:null
};
},
// 覆盖默认的上传行为
requestUpload() {},
// 向左旋转
rotateLeft() {
this.$refs.cropper.rotateLeft();
},
// 向右旋转
rotateRight() {
this.$refs.cropper.rotateRight();
},
// 图片缩放
changeScale(num) {
num = num || 1;
this.$refs.cropper.changeScale(num);
},
// 上传预处理
beforeUpload(file) {
if (file.type.indexOf("image/") == -1) {
this.$message.error("文件格式错误,请上传图片类型,如:JPG,PNG后缀的文件。");
} else {
this.file = file;
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
this.options.headImgUrl = reader.result;
};
}
},
// 实时预览
realTime(data) {
this.previews = data;
},
如果需要手动上传,代码如下,因为这个项目使用阿里云上传,所以把blob转了一下格式,你们自行根据需要改动,主要知道this.$refs.cropper.getCropBlob得到图片剪裁旋转后的文件流
submit() {
this.$refs.ruleForm.validate((valid) => {
if (valid) {
this.$refs.cropper.getCropBlob((data) => {
const time = new Date().getTime();
const fileName= time + "_" + this.file.name;
// blob转file
let file = new window.File([data], fileName, {
type: data.type,
});
this.form.file = file;
let formdata = this.formdataify(this.form);
teacherAddOrUpdate(formdata).then((res) => {
this.$message.success("新增成功");
this.visible = false;
this.getTeacherList();
});
});
}
});
},