微信小程序 -orc百度文字识别

微信小程序 -orc百度文字识别

一、开通百度文字识别功能(https://cloud.baidu.com/product/ocr)

在这里插入图片描述

创建应用
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
开通-通用文字识别(普通版),如果你的认证是企业认证的话,这里是免费使用的
在这里插入图片描述

一、微信小程序代码应用

(1)在使用页面 index.wxml 如下(示例)

   <view bindtap="chooseimg" >
  选择图片
    </view>

(2)在使用页面 index.js如下(示例)

//点击事件
  chooseimg() {
    const that = this
    wx.chooseMedia({
      count: 9,
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
       const tempFilePath =res.tempFiles[0].tempFilePath
        wx.getFileSystemManager().readFile({
          filePath: tempFilePath,
          encoding: 'base64',
          success: function (res) {
          //res.data 上传图片地址64编码
             wx.showLoading({
    		    title: '识别中...',
  			    })
    //根据图片的内容调用API获取图片文字
      that.getToken().then(res => {
        //获取token
        const token = res.data.access_token
        const detectUrl = `https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=${token}` // baiduToken是已经获取的access_Token      
        wx.request({
          url: detectUrl,
          data: {
            image: res.data
          },
          method: 'POST',
          dataType: 'json',
          header: {
            'content-type': 'application/x-www-form-urlencoded' // 必须的        
          },
          success: function (res, resolve) {
              console.log('识图片内容后: ' + res.data.words_result)
              wx.hideLoading()
          },
          fail: function (res, reject) {
            console.log('get word fail:', res.data);
            wx.hideLoading()
          },
          complete: function () {
            wx.hideLoading()
          }
        })
      })
          },
        })
      }
    })
  },

  // 获取百度access_token  
    getToken: function () {
      return new Promise(resolve => {
        var APIKEY = "刚刚创建应用的API Key"
        var SECKEY = "刚刚创建应用的Secret Key"
        var tokenUrl = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${APIKEY}&client_secret=${SECKEY}`
        var that = this;
        wx.request({
          url: tokenUrl,
          method: 'POST',
          dataType: 'json',
          header: {
            'content-type': 'application/json; charset-UTF-8'
          },
          success: function (res) { 
            return resolve(res) 
            console.log("Token获取成功", res);
          },
          fail: function (res) {
            console.log("Token获取失败", res);
            return resolve(res)
          }
        })
      })
    },
  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值