EasyAR+微信小程序识别图片开发记录

本文记录了使用EasyAR SDK与微信小程序整合进行图片识别的过程,包括所需的数据如AppId、ApiKey、Token等,以及业务流程。首先介绍了如何通过官方提供的Token或自建服务器获取动态签名加密的Token。接着详细阐述了小程序端的业务关系,如调用搜索服务识别图片的步骤和示例代码。最后提供了官方示例代码和实际操作的注意事项,帮助读者理解并实现AR图片识别功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

EasyAR+微信小程序识别图片开发记录

  1. 所需数据
  2. 业务关系
  3. 示例代码
  4. 总结

所需数据

//小程序>appid
AppId:*****
//EasyAR>
ApiKey:****
APISecret:*****
Token:*****
//微信小程序相关的业务操作-创建云识别管理-寻找云图库-密钥-小程序AR使用
CloudKey:*****
CloudURLs:*****
小程序ARToken:******
// 1.可用官方提供Token使用开发可设置Token有效天数(官方提供-ApiKey位置);
// 2.可使用自建服务器解析Sign签名,向服务器申请有效Token(动态生成)

业务关系
官方文档示例:Esayar官方微信小程序使用操作指示

  1. 动态签名加密方法:
//NodeJs服务器解析方法
var crypto = require('crypto');

function genSign(params,appSecret) {
    var paramsStr = Object.keys(params).sort().map(function(key) {
        return key+params[key];
    }).join('') + appSecret;
	console.log("排序后数据",paramsStr);
    return crypto.createHash('sha256').update(paramsStr).digest('hex');
}

let signParams = function(params, timestamp, apiKey, apiSecret) {
    params.timestamp = new Date().getTime();
    params.apiKey = encodeURI(apiKey);
	params.expires=3600;	
    params.signature = genSign(params, apiSecret);
    return params;
};
//调用signParams()插入相关数据的ApiKey+ApiSecret[注意!非小程序ar的key以及密钥]
//将获取到的数据传入Token查询接口即可获取所需Token数据
//微信小程序获取使用:https://uac-na1.easyar.com/Token/v2【官方默认的请求接口/不携带V2获取数据有所不同,结构不同吗,不过均可获取Token的效果值】
//官方示例地址:https://help.easyar.cn/EasyAR%20APIKey/api/get-token.html
//中国1区: https://uac.easyar.com
//北美1区: https://uac-na1.easyar.com

Token[动态获取-官方提供]
小程序端使用示例
操作描述:

  1. 打开相机权限
  2. 截取某帧生成Canvas绘制图片
  3. 转换Base64格式图片,向Search服务发起请求
  4. 请求地址:https://cn1-crs.easyar.com:8443/search/
  5. 获取反馈的数据,target与图库表的某个图片ID对应,判断是否识别成功,然后做相关操作业务

微信小程序端示例代码

示例代码为官方提供Git地址代码截取
//js区域
// pages/recognition/recognition.js
import upng from '../../UPNG.js'
Page({
  data: {
    height: '360',
    width: '20',
    status:false,
    scanStatus: 'none',
    msg: "请点击识别图片",
    src: '',
    imgurl:"",
    listener: null,
    isReuqest: false,
    canvasWidth: '10',
    canvasHeight:'10',
  },

  onLoad: function (options) {
    this.ctx = wx.createCameraContext();

    wx.getSystemInfo({
      success: res => {
        this.setData({ height: res.windowHeight * 0.8, width: res.windowWidth});
      }
    });
  },

  stopScan: function () {
    this.setData({ scanStatus: 'none' });
  },

  onShow: function () {
    this.setData({ msg: '请点击识别图片' });
  },

  error: function (e) {
    this.setData({ msg: '打开摄像头失败,请点击“立即体验' });
  },


  searchPhoto: function(imageBase64) {
    let that = this;
    wx.showLoading({
      title: '识别中...',
    })
    wx.request({
      url: 'https://cn1-crs.easyar.com:8443/search/', 
      data: {
        image: imageBase64,
        notracking: "true",//下方Token为小程序ARtoken的时候,不需要此字段
        appId: "ApiKey",//同notracking后注释一样
      },
      header: {
        'Authorization':'Token',//可填数据ApiToken or 小程序ARtoken
        'content-type': 'application/json' // 默认值
      },
      method: 'POST',
      success(res) {
        console.log(res);
        that.setData({isReuqest: false});
        if (res.data.statusCode == 0) {
          that.listener.stop();
          that.setData({ msg: '识别成功'});
          wx.hideLoading()
        }else{
          wx.hideLoading();
          if(res.data.statusCode=="21"){
            that.status = false;
            that.setData({ msg:res.data.result.message, isReuqest:true});
            wx.showToast({
              title:res.data.result.message,
              icon:"none"
            })
          }
        }
      },
      fail(err) {
        console.log(err)
        that.status = false;
        that.setData({ msg: '识别失败,请点击重试', isReuqest: false});
      }
    })
  },

  transformArrayBufferToBase64: function (frame) {
    console.log(frame,"参数")
    const data = new Uint8ClampedArray(frame.data);
    this.setData({isReuqest: true});
    let pngData = upng.encode([frame.data], frame.width, frame.height, 16, 0);
    let base64 = wx.arrayBufferToBase64(pngData);
    console.log(base64);
    this.setData({imgurl:base64});
    this.searchPhoto(base64)
  },

  takePhoto: function (e) {
    console.log(`点击开启`);
    if (this.status) return;
    this.status = true;
    const context = wx.createCameraContext()
    this.listener = context.onCameraFrame((frame) => {
      if(!this.data.isReuqest) {
        this.transformArrayBufferToBase64(frame);
      }
    });
    this.listener.start({
      success: () => {
        console.log('监听成功')
      },
      fail: (err) => {
        console.log('监听失败')
        console.log(err)
      }
    })
  }
})

页面代码

<camera device-position="back"  frame-size="small"  flash="off" binderror="error" style="width: 100%; height: {{height}}px"></camera>
<view class='recognition-container'>
  <view class="btn-area">
      <button type="primary" bindtap="takePhoto">{{msg}}</button>
  </view>
  <canvas style="width: {{width}}px; height: {{height}}px; opacity: 0" canvas-id="firstCanvas"></canvas>
</view>
<textarea name="" id="" cols="30" rows="10">
{{imgurl}}
</textarea>
<image src="{{imgurl}}"></image>
//样式
/* pages/recognition/recognition.wxss */
.recognition-container{
  position: relative;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.btn-area{
  position: relative;
  right: 20px;
  left: 20px;
  bottom: 10vh;
  z-index: 1000;
}

官方提供示例Demo
示例1:https://github.com/z-92/EasyAR-miniprogram-WebAR-Demo.git
示例2:https://github.com/zi-kang/EasyAR-miniprogram-WebAR-Demo.git
博主使用代码为示例2描述的TokenType
业务完结
如有不理解的地方,可用留言,Mark!

评论 33
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

曲江涛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值