1.首先要获取access_token;
2.得到access_token之后,这个access_token是为了请求百度人像分割接口时候需要的;
<template> <div> <h2>百度Api人像分割</h2> <hr> <Base64View @sendBase64="sendBase64" /> <img :src="result" alt="" width="200"> <span v-show="flag" style="color:red">请稍等~~~~~~~~~~~~~~~~</span> </div> </template> <script> import qs from "qs"; import Base64View from "../components/Base64View.vue"; export default { components: { Base64View }, data() { return { info: 12312, access_token: "", image: "", result: "", flag: false } }, created() { this.$Axios.post("/api/oauth/2.0/token", qs.stringify({ grant_type: "client_credentials", client_id: "xxxx", client_secret: "xxxx" })).then((res) => { console.log(res); this.access_token = res.data.access_token }) }, methods: { sendBase64(val) { this.flag = true; console.log(this.access_token); this.image = encodeURI(val) this.$Axios.post("/aa/rest/2.0/image-classify/v1/body_seg?access_token=" + this.access_token, qs.stringify({ image: this.image }) ).then(res => { this.flag = false; console.log(res.data.foreground); this.result = "data:image/png;base64," + encodeURIComponent(res.data.foreground) }) } } } </script> <style> </style>
3.因为人像分割接口的参数需要image作为参数,
4.按着要求需要把图片转成base64然后在urlencode,所以写了一个图片转base64的组件,如下
<template>
<div>
<input type="file" :value="fileValue" id="upImageFile" @change="ImageToBase64">
<img :src="iconBase64" alt="" width="200" />
</div>
</template>
<script>
export default {
data() {
return {
fileValue: "",
iconBase64: ""
}
},
methods: {
//将本地图片转化为Base64
ImageToBase64() {
let files = document.getElementById('upImageFile').files[0];
var reader = new FileReader()
reader.readAsDataURL(files)
reader.onload = () => {
console.log('图片转base64结果:' + reader.result)
this.iconBase64 = reader.result;
this.$emit("sendBase64", this.iconBase64);
}
reader.onerror = function (error) {
console.log('Error: ', error)
}
}
}
}
</script>
5.通过自定义事件把base64传给父组件,父组件中当请求的参数使用;
6.最后得到请求结果直接使用即可