vue使用vue-cropper裁剪图片
首先先来看下效果
屏幕录制2022-04-20 14.59.01
vue-cropper
github地址:https://github.com/xyxiao001/vue-cropper
安装
npm install vue-cropper
yarn add vue-cropper
在入口文件中引用
import {VueCropper} from 'vue-cropper'
components: { VueCropper }
使用
在项目使用的是ElementUI
<el-dialog :visible.sync="dialogStatusVisible" @open="cropperOpen" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
<div class="dialogtitle">
<div>图片裁剪</div>
<img class="closetitle" @click.stop="dialogStatusVisible = false" src="@/assets/close.png" alt="">
</div>
<div class="dialogbody">
<div>
<div style="margin-top:20px;height:400px;">
<div class="cropper" style="text-align:center;height:400px;">
<vueCropper
ref="cropper"
:img="option.img"
:outputSize="option.outputSize"
:outputType="option.outputType"
:info="option.info"
:canScale="option.canScale"
:autoCrop="option.autoCrop"
:autoCropWidth="option.autoCropWidth"
:autoCropHeight="option.autoCropHeight"
:fixed="option.fixed"
:fixedBox="option.fixedBox"
:fixedNumber="option.fixedNumber"
></vueCropper>
</div>
</div>
<div class="btnclose">
<el-button class="btn closebtn" plain @click.stop="dialogStatusVisible = false">取消</el-button>
<el-button class="btn surebtn" type="primary" @click.stop="sureStatus">确认</el-button>
</div>
</div>
</div>
</el-dialog>
在data中
dialogStatusVisible:false,
option: {
img: '', // 裁剪图片的地址
info: true, // 裁剪框的大小信息
outputSize: 1, // 裁剪生成图片的质量
outputType: 'png', // 裁剪生成图片的格式
canScale: false, // 图片是否允许滚轮缩放
autoCrop: true, // 是否默认生成截图框
autoCropWidth: 212, // 默认生成截图框宽度
autoCropHeight: 106, // 默认生成截图框高度
fixedBox: false, // 固定截图框大小 不允许改变
fixed: false, // 是否开启截图框宽高固定比例
fixedNumber: [2, 1], // 截图框的宽高比例
full: false, // 是否输出原图比例的截图
canMoveBox: true, // 截图框能否拖动
original: true, // 上传图片按照原始比例渲染
centerBox: false, // 截图框是否被限制在图片里面
infoTrue: true, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
canMove: true,
},
在js中使用
sureStatus(){
// 获取截图的 blob 数据
this.$refs.cropper.getCropBlob((blob) => {
console.log(blob)
this.dialogStatusVisible = false
})
// 获取截图的 base64 数据
this.$refs.cropper.getCropData(data => {
console.log("获取 base64 数据:", data)
console.log(this.base64ToFile(data,'1.png'))
//这里写上传给后端的逻辑
let that = this
let form = new FormData()
form.append('file', that.base64ToFile(data,'1.png'))
ossUpload(form).then(res=>{
console.log(res)
})
})
},
//解码base64,以file上传给后端
base64ToFile(urlData, fileName) {
let arr = urlData.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bytes = atob(arr[1]); // 解码base64
let n = bytes.length
let ia = new Uint8Array(n);
while (n--) {
ia[n] = bytes.charCodeAt(n);
}
console.log(mime,ia)
return new File([ia], fileName, { type: mime });
},
cropperOpen(){
this.option.img = '图片地址'
},
觉得有用动动你的小手点个赞点个关注吧😁