微信小程序使用百度AI识别接口的通用封装Promise详解

2023-04-03 710阅读

温馨提示:这篇文章已超过388天没有更新,请注意相关的内容是否还可用!

百度AI开放平台是目前市场上主流开放接口平台之一,新用户还可领取免费资源(适合我这种勤俭节约的人),本篇就来介绍如何对百度AI的开放接口进行通用封装。

百度接口调用封装(Promise)

此封装主要是针对需要上传图片识别的接口,比如翻译,身份证识别,车牌识别等等。其他不需要上传图片的接口,把wx.chooseMedia那部分去掉就可以。

前提准备:

  • 注册百度AI账号

  • 领取对应资源

  • 创建应用,拿到client_id和client_secret(本封装方法的access_token是在小程序前端获取的,如果是把access_token放后端,通过调用后端接口获取的,url就换成自己的后端接口即可)。

  • 封装代码:

先在utils文件夹下新增BadiduOcr.js文件,代码如下:

/* 百度识别封装 */

function BadiduOcr() {
	return new Promise(function (resolve, reject) {
		// 图片识别
		wx.chooseMedia({ // 车牌图片/拍照
			count: 1, // 最多可以选择的文件个数
			mediaType: ['image'], //文件类型
			sizeType: ['original', 'compressed'], //是否压缩所选文件
			sourceType: ['album', 'camera'], // 图片来源
			success(res) { //调用照片选择成功的回调函数
				console.log(res);
				//图片编码部分核心代码 上传到接口需要将图片转为base64格式
				wx.getFileSystemManager().readFile({
					filePath: res.tempFiles[0].tempFilePath,
					encoding: 'base64', //编码格式
					success(ans) {
						// console.log(ans.data)
						wx.showLoading({
							title: '识别中'
						})
						//ans.data:保存了图片转码之后的数据
						// 1.请求获取百度的access_token
						wx.request({
							//url中的&client_id=client-i&client_secret=client—s中的参数client-i和client—s需要申请百度识别的账号和密码,具体申请流程参考上面
							url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=你的client_id&client_secret=你的client_secret',
							data: {}, //请求参数,此处没有参数,则置空
							header: {
								'content-type': 'application/x-www-form-urlencoded' // 默认值
							},
							success(rep) {
								var access_token = rep.data.access_token;
								console.log("access_token:", access_token)
								// 2.带着token与转码后的图片编码请求百度OCR接口,对图片进行识别
								wx.request({
									url: 'https://aip.baidubce.com/百度识别的具体接口?access_token=' + access_token,
									method: 'POST',
									header: {
										'Content-Type': 'application/x-www-form-urlencoded'
									},
									data: {
										image: ans.data, //ans.data:图片编码
									},
									success(_res) {
										wx.hideLoading();
										resolve(_res)
										console.log("识别成功:", _res)
									},
									fail(_res) {
										wx.hideLoading();
										wx.showToast({
											title: '请求出错',
											icon: 'none'
										})
										reject(_res)
									}
								})
							},
							fail(rep) {
								wx.hideLoading();
								wx.showToast({
									title: '请求出错',
									icon: 'none'
								})
								reject(rep)
							}

						});
					},
					fail(res) {
						wx.hideLoading();
						wx.showToast({
							title: '所选图片编码失败,请重试',
							icon: 'none'
						})
						reject(res)
					}
				})

			},
			fail(res) {
				wx.hideLoading();
				wx.showToast({
					title: '图片选择失败,请重试',
					icon: 'none'
				})
				reject(res)
			}
		})
	})
}
module.exports = {
	BadiduOcr: BadiduOcr
}
  • 调用

   <button width="200rpx" height="64rpx" size="{{30}}" bindtap="getNum" bold>百度识别</tui-button>
import {
    BadiduOcr
} from '../../utils/BadiduOcr'
Page({
	 /* 选择文件,识别 */
    getNum() {
        BadiduOcr().then(res => {
            console.log(res);
            if (res.statusCode == 200) {
                wx.showToast({
                    title: '识别成功',
                })
                
            }
        }).catch(err => {
            console.log(err);
        })
    },
})