老规矩先了解插件 vue-cropper官方链接:https://github.com/xyxiao001/vue-cropper
下载依赖 npm install vue-cropper
1、 封装组件
<template>
<div>
<el-dialog
:visible="visible"
:append-to-body="true"
:close-on-click-modal="false"
width="700"
class="image-cropper-dialog"
@close="visible = false"
>
<vue-cropper
ref="imageCropper"
:img="url"
:auto-crop-width="autoCropWidth"
:auto-crop-height="autoCropHeight"
:auto-crop="true"
:fixed="false"
:fixed-number="[1, 1]"
:fixed-box="true"
:output-size="1"
output-type="png"
/>
<template #footer>
<span class="dialog-footer">
<el-button class="common-btn cancel" @click="onCancel">取 消</el-button>
<el-button class="common-btn confirm" type="primary" @click="onConfirm">完 成</el-button>
</span>
</template>
</el-dialog>
</div>
</template>
<script>
import { VueCropper } from "vue-cropper";
export default {
name: "ImageCropperModal",
components: {
VueCropper
},
props: {
visible: {
type: Boolean,
default: false
},
url: {
type: String,
default: ""
},
autoCropWidth: {
type: String,
default: `${104 * 4}`
},
autoCropHeight: {
type: String,
default: `${104 * 4}`
}
},
methods: {
onCancel() {
this.$emit("cancel");
},
onConfirm() {
this.$refs.imageCropper.getCropBlob(blob => {
this.$emit("confirm", blob);
});
}
}
};
</script>
<style lang="less" scoped>
.image-cropper-dialog {
.vue-cropper {
height: 500px;
}
}
</style>
2、组件使用
<template>
<input type="file" v-on:change="onUpload()" ref="fileInput" />
<div class="el-upload__tip">*注:上传logo尺寸最大 58*58</div>
<imageCropperCodal
:visible="cropperVisible"
:url="file"
:auto-crop-width="autoCropWidth"
:auto-crop-height="autoCropHeight"
@cancel="cropperVisible = false"
@confirm="onConfirm"
/>
</template>
<script>
import imageCropperCodal from "./imageCropperCodal.vue";
export default {
components: {
imageCropperCodal
},
data(){
return{
files: [],
cropperVisible: false,
autoCropWidth: "56",
autoCropHeight: "56",
file: "",
fileName: ""}
}
methods:{
async onUpload(e) {
const file = this.$refs.fileInput.files[0];
console.log(file);
const fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = () => {
this.file = fileReader.result;
this.cropperVisible = true;
this.fileName = file.name;
};
},
async onConfirm(files) {
var aa = this.blobToBase64(files);
console.log();
aa.then(res => {
console.log(res);
potsfile(res);
});
this.cropperVisible = false;
},
async blobToBase64(blob) {
let buffer = await blob.arrayBuffer();
let bytes = new Uint8Array(buffer);
console.log(bytes);
let binary = "";
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
var base64 = "data:image/webp;base64," + window.btoa(binary);
return base64;
}
}
</script>
onConfirm是裁剪完的图片 blobToBase64将图片转成base64