vue实现图片裁剪上传
Vue 实现图片裁剪上传的方法
使用 vue-cropper 库
安装 vue-cropper 库:
npm install vue-cropperjs
在组件中引入并使用:
<template>
<div>
<input type="file" @change="uploadImg" accept="image/*">
<vue-cropper
ref="cropper"
:img="imgSrc"
:autoCrop="true"
:autoCropWidth="200"
:autoCropHeight="200"
></vue-cropper>
<button @click="cropImg">裁剪</button>
</div>
</template>
<script>
import VueCropper from 'vue-cropperjs';
import 'cropperjs/dist/cropper.css';
export default {
components: { VueCropper },
data() {
return {
imgSrc: ''
};
},
methods: {
uploadImg(e) {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
this.imgSrc = event.target.result;
};
reader.readAsDataURL(file);
},
cropImg() {
this.$refs.cropper.getCroppedCanvas().toBlob((blob) => {
const formData = new FormData();
formData.append('file', blob, 'cropped.png');
// 上传 formData 到服务器
});
}
}
};
</script>
使用 cropperjs 直接集成
安装 cropperjs:
npm install cropperjs
在组件中使用:
<template>
<div>
<input type="file" @change="uploadImg" accept="image/*">
<img ref="image" src="">
<button @click="cropImg">裁剪</button>
</div>
</template>
<script>
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';
export default {
data() {
return {
cropper: null,
imgFile: null
};
},
mounted() {
this.cropper = new Cropper(this.$refs.image, {
aspectRatio: 1,
viewMode: 1
});
},
methods: {
uploadImg(e) {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
this.$refs.image.src = event.target.result;
this.cropper.replace(event.target.result);
};
reader.readAsDataURL(file);
this.imgFile = file;
},
cropImg() {
this.cropper.getCroppedCanvas().toBlob((blob) => {
const formData = new FormData();
formData.append('file', blob, 'cropped.png');
// 上传 formData 到服务器
});
}
}
};
</script>
使用 Element UI 的 Upload 组件
结合 Element UI 的 Upload 和 cropperjs:
<template>
<el-upload
action="#"
:auto-upload="false"
:on-change="handleChange"
:show-file-list="false"
>
<el-button>选择图片</el-button>
</el-upload>
<img ref="image" src="">
<el-button @click="cropImg">裁剪并上传</el-button>
</template>
<script>
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';
export default {
data() {
return {
cropper: null
};
},
methods: {
handleChange(file) {
const reader = new FileReader();
reader.onload = (event) => {
this.$refs.image.src = event.target.result;
if (this.cropper) {
this.cropper.destroy();
}
this.cropper = new Cropper(this.$refs.image, {
aspectRatio: 1
});
};
reader.readAsDataURL(file.raw);
},
cropImg() {
this.cropper.getCroppedCanvas().toBlob((blob) => {
const formData = new FormData();
formData.append('file', blob, 'cropped.png');
// 上传 formData 到服务器
});
}
}
};
</script>
注意事项
- 图片上传需要后端接口支持,通常使用 FormData 格式上传。
- 裁剪后的图片可以通过
toBlob或toDataURL方法获取。 - 移动端可能需要额外处理手势和缩放问题。







