安装
npm install vue-image-crop-upload
组件代码:
<template>
<div id="app">
<a class="btn" @click="toggleShow">设置头像</a>
<my-upload field="img" @crop-success="cropSuccess" v-model="show" :width="200" :height="200" img-format="png" :size="size"></my-upload>
<img :src="avatar">
</div>
</template>
<script>
import 'babel-polyfill'; // es6 shim
import myUpload from 'vue-image-crop-upload';
export default {
data() {
return {
avatar: "",
show: false,
size:2.1
}
},
components: {
"my-upload": myUpload
},
methods: {
toggleShow() {
this.show = !this.show;
},
cropSuccess(imgDataUrl) {
// imgDataUrl其实就是经过base64转码过的图片
this.avatar = imgDataUrl;
console.log(imgDataUrl)//这里打印出来的是base64格式的资源,太长了
//base64转blob格式
let arr = imgDataUrl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
let bdata = new Blob([u8arr], { type: mime })
// console.log(new Blob([u8arr], { type: mime })) ;//这里打印base64转成blob的资源,根据自己的项目需求去转吧
}
}
}
</script>
<style>
</style>