使用小程序实现识别图像文字并提取

一、文章前言

此文主要实现通过小程序将图片中的文字进行识别并提取,在生活中经常会碰到需要从某个网站或者图片上获得一些文案或资料的场景,如果来回切换靠人工码字可能有点儿累,可以开发一个小工具提高下自己的效率。

二、具体流程及准备

2.1、注册百度开放平台及微信公众平台账号。
2.2、下载及安装微信Web开发者工具。
2.3、如需通过SDK调用及需准备对应语言的开发工具。

三、开发步骤

3.1、访问百度开放平台选择文字识别并领取免费资源。
在这里插入图片描述
3.2、填写表单所需要的各项信息创建应用。
在这里插入图片描述
3.3、创建完毕后回到应用列表,将API Key 以及Serect Key复制出来,后面我们需要通过这些凭证来获取Token。

在这里插入图片描述

3.4、信息准备好后,打开微信开发者工具,新建项目,选择不使用模板、不使用云服务。
在这里插入图片描述
3.5、在pages文件夹下面创建一个文件夹并新建对应的page文件。
在这里插入图片描述
3.6、在JS文件中的onLoad函数中请求获取Token的接口,这时候就需要用到我们刚才所申请的ApiKey等信息; 了。
在这里插入图片描述
在这里插入图片描述

/**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
    
    let that = this;
    let ApiKey='这里填你所申请的ApiKey';
    let SecretKey='这里填你所申请的SecretKey';
    wx.request({
    
    
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + ApiKey+'&client_secret='+SecretKey,
      method: 'POST',
      success: function (res) {
    
    
        that.setData({
    
    
          AccessToken:res.data.access_token
        });
      }
    });
  },

3.6、编译程序,检查接口是否有正常返回,下图所标记的字段就是我们所需要的token了,它的有效期为30天,记得要及时更新。
在这里插入图片描述
3.7、接下来需要实现选择图片及将其转换为base64的功能,因为图像识别的接口参数需要base64格式;这里需要用到wx.chooseImage以及wx.getFileSystemManager()两个函数。
在这里插入图片描述

<view class="containerBox">
  <view class="leftBtn" bindtap="loadImage">上传图片</view>
  <view class="rightBtn" bindtap="identify">图像识别</view>
</view>
  loadImage() {
    
    
    let that = this;
    wx.chooseImage({
    
    
      count: 0,
      sizeType: ['original', 'compressed'], //原图 / 压缩
      sourceType: ['album', 'camera'], //相册 / 相机拍照模式
      success(res) {
    
    
        that.setData({
    
    
          imgSrc: res.tempFilePaths[0]
        });
        //将图片转换为Base64格式
        wx.getFileSystemManager().readFile({
    
    
          filePath: res.tempFilePaths[0],
          encoding: 'base64',
          success(data) {
    
    
            let baseData = data.data; //'data:image/png;base64,' + data.data;
            that.setData({
    
    
              baseData: baseData
            });
          }
        });
      }
    })
  },

3.8、将所选择的图片在页面上进行显示,拼接参数调用图像识别接口。

<image src="{
    
    {imgSrc}}" class="showImg"></image>
参数 是否必选 类型 说明
image string 图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过10M,最短边至少15px,最长边最大8192px,支持jpg/jpeg/png/bmp格式
wx.request({
    
    
      url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=' + that.data.token, //动物
      method: 'POST',
      header: {
    
    
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
    
    
        image: that.data.baseData
      },
      success: function (identify) {
    
    
        
      }
    })
字段 类型 说明
log_id uint64 唯一的log id,用于问题定位
words_result array[] 识别结果数组
words_result_num uint32 识别结果数,表示words_result的元素个数

在这里插入图片描述

3.9、将接口所返回的识别结果及数量在页面进行展示,并增加复制功能。

  <view class="productDetailTable">
    <view class="productTableTr">
      <view class="leftTr">
        <view class="little leftTrText">文字行数:</view>
      </view>
      <view class="rightTr little">{
    
    {
    
    wordLine}}</view>
    </view>

    <view class="productTableTr" wx:for="{
    
    {resultList}}">
      <view class="leftTr">
        <view class="little leftTrText">{
    
    {
    
    item.words}}</view>
      </view>
      <view class="rightTr little">
        <view class="displayBox copyBtn" bindtap="copy" data-id='{
    
    {item.words}}'>复制</view>
      </view>
    </view>
  </view>
    wx.setClipboardData({
    
    
      //准备复制的数据
      data: e.currentTarget.dataset.id,
      success: function (res) {
    
    
        wx.showToast({
    
    
          title: '复制成功',
        });
      }
    });

四、完整代码

<!--index.wxml-->

<view class="containerBox">
  <view class="leftBtn" bindtap="loadImage">上传图片</view>
  <view class="rightBtn" bindtap="identify">图像识别</view>
</view>
<image src="{
    
    {imgSrc}}" class="showImg"></image>
<view class="result" wx:if="{
    
    {isShowDetail}}">
  <view class="resultTitle">识别结果:</view>
  <view class="productDetailTable">
    <view class="productTableTr">
      <view class="leftTr">
        <view class="little leftTrText">文字行数:</view>
      </view>
      <view class="rightTr little">{
    
    {
    
    wordLine}}</view>
    </view>

    <view class="productTableTr" wx:for="{
    
    {resultList}}">
      <view class="leftTr">
        <view class="little leftTrText">{
    
    {
    
    item.words}}</view>
      </view>
      <view class="rightTr little">
        <view class="displayBox copyBtn" bindtap="copy" data-id='{
    
    {item.words}}'>复制</view>
      </view>
    </view>
  </view>
</view>
<!--index.wxss-->
.containerBox{
    
    
  width:750rpx;
  display:flex;
  height:62rpx;
  margin-top:20rpx;
}
.leftBtn{
    
    
  width:181rpx;
  height:62rpx;
  color:#4FAFF2;
  border:1rpx solid #4FAFF2;
  border-radius:10rpx;
  text-align: center;
  line-height:62rpx;
  font-size:28rpx;
  margin-left: 158rpx;
}
.rightBtn{
    
    
  width:181rpx;
  height:62rpx;
  color:white;
  border:1rpx solid #4FAFF2;
  border-radius:10rpx;
  text-align: center;
  line-height:62rpx;
  font-size:28rpx;
  margin-left: 73rpx;
  background:#4FAFF2;
}
.showImg{
    
    
  width:310rpx;
  height:224rpx;
  margin-left:220rpx;
  margin-top:25rpx;
  border-radius:20rpx;
}
.result{
    
    
  margin-top:20rpx;
}
.resultTitle{
    
    
  margin-left:75rpx;
}
.productTableTr{
    
    
  height: 80rpx;line-height: 80rpx;border-bottom: 5rpx solid #F8F8F8;display:flex;
}
.leftTr{
    
    
  width: 583rpx;height: 80rpx;line-height: 80rpx;
}
.rightTr{
    
    
  width: 119rpx;height: 80rpx;line-height: 80rpx;color: #FF2525;font-size: 26rpx;
}
.leftTrText{
    
    
  color: #2B79F5;font-size: 28rpx;margin-left: 15rpx;width: 283rpx;
}
.productDetailTable{
    
    
  width: 702rpx;margin-left: 24rpx;border:5rpx solid #F8F8F8;border-radius: 6rpx;
}
.copyBtn{
    
    
  color:white;background:#2B79F5;border-radius:8rpx;width:100rpx;height:50rpx;margin-top:15rpx;
}
 /**
   * 页面的初始数据
   */
  data: {
    
    
    token: '',
    imgSrc: '',
    isShowDetail: false,
    resultList: [],
    baseData: '',
    wordLine: '',
  },
   /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
    
    let that = this;
    let grant_type = 'client_credentials';
    let client_id = '';
    let client_secret = '';
    wx.request({
    
    
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=' + grant_type + '&client_id=' + client_id + '&client_secret=' + client_secret,
      method: 'post',
      header: {
    
    
        'content-type': 'application/json'
      },
      success: function (res) {
    
    
        that.setData({
    
    
          token: res.data.access_token
        });
      }
    })
  },
  loadImage() {
    
    
    let that = this;
    wx.chooseImage({
    
    
      count: 0,
      sizeType: ['original', 'compressed'], //原图 / 压缩
      sourceType: ['album', 'camera'], //相册 / 相机拍照模式
      success(res) {
    
    
        that.setData({
    
    
          imgSrc: res.tempFilePaths[0]
        });
        //将图片转换为Base64格式
        wx.getFileSystemManager().readFile({
    
    
          filePath: res.tempFilePaths[0],
          encoding: 'base64',
          success(data) {
    
    
            let baseData = data.data; //'data:image/png;base64,' + data.data;
            that.setData({
    
    
              baseData: baseData
            });
          }
        });
      }
    })
  },

猜你喜欢

转载自blog.csdn.net/weixin_42794881/article/details/127282221