小程序使用百度图片提取文字api

微信小程序上实现拍照或者使用相册内图片,提取识别文字,可以使用百度提供的识别图文的api接口
首先去百度注册
https://ai.baidu.com/tech/ocr?track=cp:ainsem|pf:pc|pp:878-chanpin-wenzishibie|pu:wenzishibie|ci:|kw:10522915
我选用的是普通场景的产品,在最近访问的产品下面可以新增产品,也可以在已建产品里进入,点击创建应用
在这里插入图片描述
在这里插入图片描述
填写基本必要信息,就有了自己的项目和key,下面是js文件,函数不多,注释我写在代码内

// pages/wenzi/wenzi.js
const app = getApp()
Page({

/**
* 页面的初始数据
*/
data: {
  imageData: '../../images/wenzi.png',
items: null,
},

/**
* 生命周期函数--监听页面加载,调用doupload函数,真机调试可以使用摄像头,选择拍照或者相册内图片
*/
onLoad: function (options) {
  this.doUpload()
},
//获取百度api接口,key好像是一个月一换注意更新
getBaiduToken: function(){
  console.log("getBaidu");
  var apiKey = 'xxxxxx';    
  var secKey = 'xxxxxx';    
  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'       
         'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
 
      },        
      success: function(res){            
          console.log("[BaiduToken获取成功]",res);            
          that.setData({                
              baiduToken: res.data.access_token                            })        
      },        
      fail: function(res){            
          console.log("[BaiduToken获取失败]",res);
      }    
  })  
}, 
//扫描图片,图片识别需要从转换格式
scanImageInfo: function(imageData){    // 这里的imageData是图片转换成base64格式的数据
  console.log("that.data.baiduToken");
  var that = this;
  const detectUrl = `https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=${that.data.baiduToken}`;   // baiduToken是已经获取的access_Token

    return new Promise(function(resolve,reject){        
      wx.request({            
          url: detectUrl,            
          data: {                
              image: imageData            
          },            
          method: 'POST',            
          dataType: 'json',            
         header:{                
              'content-type': 'application/x-www-form-urlencoded'    // 必须的        
          },        
       
          success: function(res, resolve){              
              console.log('get word success:',res.data);              
              var word = res.data.words_result              
              console.log(word);     
              that.setData({
                items:word
              })       
          },            
          fail : function(res,reject){              
              console.log('get word fail:',res.data);                       },            

      })
  }) 
} ,
// 上传图片  
doUpload: function () {
  var that = this    
  that.getBaiduToken()    // 提前获取access_Token
  // 选择图片,拍照或从相册中获取
  wx.chooseImage({      
      count: 1,      
      sizeType: ['compressed'],      
      sourceType: ['album', 'camera'],      
      success: function (res) {
          wx.showLoading({          
              title: '上传中',        
          })
              const filePath = res.tempFilePaths[0]                
              // 上传图片        
              wx.getFileSystemManager().readFile({          
                  filePath: filePath,          
                  encoding: 'base64',          
                  success: function(res) {            
                      console.log("[读取图片数据success]",res.data);            
                      that.scanImageInfo(res.data);    // 调用百度API解析图片获取文字  
                  },
                 
                  fail: function(res){            
                      console.log("[读取图片数据fail]",res)          
                  },            
                  complete: function(res){            
                      wx.hideLoading()          
                  }    
                })
              }
            })
          },
          //提交我将文字与做好的数据库进行比对输出
submit(){
  
  for (var i = 0; i < this.data.items.length; i++)
    { console.log("submit"+this.data.items[i].words)
   var name=this.data.items[i].words
    wx.cloud.database().collection("test").where({
     name: wx.cloud.database().RegExp({
        regexp:name,
        //i不区分大小写
        option:"i"
       
      })
    }).get().then(res => {
    console.log("搜索结果", res.data[0].password)
  
    })
}
}

})

页面文件比较简单

<view class="view_main">
<image class="image_type" src="{{imgPath}}" mode="aspectFit"></image>
<button class="button_type" bindtap="chooseimg">拍照/相册</button>

<view class="view_items">
<text wx:for="{{items}}" wx:key="{{item}}" selectable='true' class="text_son">
{{item.words}}
</text>
</view>
<button class="button_type" bindtap="submit">提交</button>
</view>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值