微信小程序调用百度智能云API(菜品识别)

一、注册后生成应用列表创建应用

二、找到当前所需使用的api菜品识别文档

三、点链接看实例代码

这里需要使用到如下几个参数(如下),其他的参数可以不管

  1. client_id : 就是创建应用后的API Key
  2. client_secret: 就是创建应用后的Secret Key
  3. image: 需要用图片转换后的base64
  4. url : 需要用到图片的线上地址,不能使用本地ip地址

调用成功后会如下图返回数据,当前使用以下三个数据

javascript 复制代码
   calorie: "",//卡路里
   name: "",   //菜名
   probability: ""//置信度值

四、实例调用分布代码

调用代码分解

  1. 先上传图片后获取本地图片路径
javascript 复制代码
async afterRead(event) {
 wx.showLoading()
    const {
        file
    } = event.detail
    const {
        personPhoto = []
    } = this.data;
    personPhoto.push({   
        ...file,
        url: file.url
    });
    this.setData({
        personPhoto: personPhoto  //照片回显在页面上显示
    });
    const data = await this.getBase64URL(event.detail.file.url)    //调用获取base64

}
  1. 后去上传的图片后获取base64图片地址
javascript 复制代码
    //获取bas464地址
    getBase64URL(file) {
        return new Promise((resolve, reject) => {
            wx.getFileSystemManager().readFile({
                filePath: file, //要读取的文件的路径 (本地路径)
                encoding: "base64", //指定读取文件的字符编码,如果不传 encoding,则以 ArrayBuffer 格式读取文件的二进制内容
                success(res) {
                    // encodeURIComponent 可把字符串作为URI 组件进行编码。其返回值URIstring 的副本,其中的某些字符将被十六进制的转义序列进行替换
                    resolve( encodeURIComponent(res.data))   //这里记得把base64转换一遍,否则会报错
                },
                fail(error) {
                    console.log(error);
                }
            })
        })


    },
  1. 去获取token
javascript 复制代码
    //根据参数获取token
    getAccessToken() {
        const params = {
            grant_type: 'client_credentials',
            client_id: 'q9NvyRRPAAWtEnUQGYztWIoY',
            client_secret: 'wGbmuZmSiMUKuoZsCrj7xbLJPeigivUR'
        }
        return new Promise((res, rej) => {
            wx.request({
                url: getImgToken,
                method: "POST",
                data: params,
                header: {
                    'content-type': 'application/x-www-form-urlencoded',
                },
                success(obj) {
                    if (obj.statusCode == 200) {
                        res(obj.data.access_token)
                    }
                },
                fail(err) {
                    rej({
                        msg: '网络错误',
                        detail: null
                    });
                }
            })
        })
    },
  1. 去调用获取数据的接口
javascript 复制代码
  const _this = this
        wx.request({
            url: 'https://aip.baidubce.com/rest/2.0/image-classify/v2/dish?access_token=' + await _this.getAccessToken(),
            method: "POST",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: `image=${data}`,
            success(obj) {
                if (obj.statusCode == 200) {
                    if (obj.data.result && obj.data.result.length > 0) {
                        obj.data.result.forEach( item =>{
                            item.probability = (item.probability*100).toFixed(2)
                        })
                        _this.setData({
                            result: obj.data.result
                        })
                    } else {
                        wx.showToast({
                          title: '未识别出菜品',
                          icon:'none'
                        })
                        _this.setData({
                            result:[]
                        })
                    }
                }
                 wx.hideLoading()
            },
            fail(err) {
                rej({
                    msg: '网络错误',
                    detail: null
                });
                wx.hideLoading()
            }
        })

五、上实图效果

六、完整实例调用代码

javascript 复制代码
    //图片上传回调函数
    async afterRead(event) {
        wx.showLoading()
        const {
            file
        } = event.detail
        const {
            personPhoto = []
        } = this.data;
        personPhoto.push({   
            ...file,
            url: file.url
        });
        this.setData({
            personPhoto: personPhoto  //照片回显在页面上显示
        });
        const data = await this.getBase64URL(event.detail.file.url)    //调用获取base64
        const image = 'https://picnew9.photophoto.cn/20141014/cuijiaozhuertupian-12936350_1.jpg' //测试使用地址
        const _this = this
        wx.request({
            url: 'https://aip.baidubce.com/rest/2.0/image-classify/v2/dish?access_token=' + await _this.getAccessToken(),
            method: "POST",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: `image=${data}`,
            success(obj) {
                if (obj.statusCode == 200) {
                    if (obj.data.result && obj.data.result.length > 0) {
                        obj.data.result.forEach( item =>{
                            item.probability = (item.probability*100).toFixed(2)
                        })
                        _this.setData({
                            result: obj.data.result
                        })
                    } else {
                        wx.showToast({
                          title: '未识别出菜品',
                          icon:'none'
                        })
                        _this.setData({
                            result:[]
                        })
                    }
                }
                 wx.hideLoading()
            },
            fail(err) {
                rej({
                    msg: '网络错误',
                    detail: null
                });
                wx.hideLoading()
            }
        })
    },
    //获取bas464地址
    getBase64URL(file) {
        return new Promise((resolve, reject) => {
            wx.getFileSystemManager().readFile({
                filePath: file, //要读取的文件的路径 (本地路径)
                encoding: "base64", //指定读取文件的字符编码,如果不传 encoding,则以 ArrayBuffer 格式读取文件的二进制内容
                success(res) {
                    // encodeURIComponent 可把字符串作为URI 组件进行编码。其返回值URIstring 的副本,其中的某些字符将被十六进制的转义序列进行替换
                    resolve( encodeURIComponent(res.data))   //这里记得把base64转换一遍,否则会报错
                },
                fail(error) {
                    console.log(error);
                }
            })
        })


    },
    //根据参数获取token
    getAccessToken() {
        const params = {
            grant_type: 'client_credentials',
            client_id: 'q9NvyRRPAAWtEnUQGYztWIoY',
            client_secret: 'wGbmuZmSiMUKuoZsCrj7xbLJPeigivUR'
        }
        return new Promise((res, rej) => {
            wx.request({
                url: getImgToken,
                method: "POST",
                data: params,
                header: {
                    'content-type': 'application/x-www-form-urlencoded',
                },
                success(obj) {
                    if (obj.statusCode == 200) {
                        res(obj.data.access_token)
                    }
                },
                fail(err) {
                    rej({
                        msg: '网络错误',
                        detail: null
                    });
                }
            })
        })
    },

l

七:其他说明

  1. 在概览中查看使用量服务列表
  1. 接口报错可查看错误码表错误码表

    制作不易,觉得用的上的还请麻烦点个关注,赞一个呗
相关推荐
志遥5 小时前
我把 Sentry 接进了 7 端小程序:从异常捕获、Breadcrumb 到 Source Map 定位
微信小程序·监控
云起SAAS6 小时前
在线客服系统源码 | 支持PC管理端+H5访客端+实时聊天
微信小程序·ai编程·看广告变现轻·在线客服系统源码
2501_933907216 小时前
如何通过上海本凡科技获得优质的小程序开发服务?
科技·微信小程序·小程序
计算机徐师兄7 小时前
Java基于微信小程序的青少年科普教学系统【附源码、文档说明】
java·微信小程序·青少年科普教学系统小程序·java青少年科普教学小程序·青少年科普教学微信小程序·青少年科普教学小程序·科普教学微信小程序
花卷HJ1 天前
微信小程序国际化完整方案
微信小程序·小程序·notepad++
nhc0881 天前
贵阳纳海川科技・上门洗车行业解决方案
科技·微信小程序·软件开发·小程序开发
hashiqimiya1 天前
微信小程序--动态切换登录注册标签页
微信小程序·小程序
hashiqimiya1 天前
微信小程序--获取验证码设计倒计时灰白色
微信小程序·小程序
2501_933907211 天前
宁波小程序公司提供专业的小程序开发服务
科技·微信小程序·小程序
扶苏10021 天前
记一次 uni-app开发微信小程序 textarea 的“伪遮挡”踩坑实录
微信小程序·小程序·uni-app