小程序 -条码识别和图像ocr识别

应用场景

用户通过扫描条码,或者拍照,上传图片,可以查询某个产品的信息

条码实现

使用API : uni.scanCode({}),成功之后,会返回barcode。
然后将此barcode传递到相应的页面(因为调用接口,需要barcode) 
  // 允许从相机和相册扫码
      uni.scanCode({
        success: async res => {
          console.log("条码类型:" + res.scanType);
          console.log("条码内容:" + res.result);
          this.qRCodeMsg = res.result;
          // 登陆接口例子
          const data = await searchApi(this.qRCodeMsg);
          uni.navigateTo({
            url: `/pages/scanResults/index?barcode=${this.qRCodeMsg}`
          });
        },
        fail: res => {
          console.log("抱歉,商品不存在");
        }
      });

拍照实现

使用API :uni.chooseImage({}),成功之后,会返回当前图片的路径,将此图片路径传到响应的页面(因为图像ocr识别接口,需要这个参数)
  // 只允许通过相机扫码
      uni.chooseImage({
        count: 1, //默认9
        sizeType: ["original", "compressed"], //可以指定是原图还是压缩图,默认二者都有
        sourceType: ["album", "camera"], //从相册选择
        success: async res => {
          console.log(res);
          this.path = res.tempFilePaths[0];
          uni.navigateTo({
            url: `/pages/discern/index?image=${this.path}`
          });
        }
      });

题外话

1:一般图片太大,需要转base64

const params = {
        image: wx.getFileSystemManager().readFileSync(this.image, "base64")
      };

2: 接口返回的数据,要分两类的处理

 for (var i = 0; i < this.getList.length; i++) {
          if (this.getList[i].ingredientType == 2) {
            this.getYList.push(this.getList[i]);
          }
          if (this.getList[i].ingredientType == 1) {
            this.getCList.push(this.getList[i]);
          }
        }

3:对于NetWork里面error的处理,可以通过tyr catch 的形式来捕获

 try {
        const data = await ocrApi(params);
        console.log("拍照数据", data);
        if (data == "") {
          this.hasData = false;
        }
        this.getList = data;
        // 成分是1 原料是2
        // var getCList = [];
        // var getYList = [];
        for (var i = 0; i < this.getList.length; i++) {
          if (this.getList[i].ingredientType == 2) {
            this.getYList.push(this.getList[i]);
          }
          if (this.getList[i].ingredientType == 1) {
            this.getCList.push(this.getList[i]);
          }
        }
      } catch (err) {
        console.log("错误异常", err);
        if (err.data.code == 1) {
          this.hasData = false;
        }
      }

4: 布局,让每一行的高度都是居中的,就不要设置行高了。这样多行可以,但是单行会有问题。使用flex的align-items:center就ok

5:uni里面,图片变性了,拉长了。里面有非常好用的

mode=''aspectFit"
	保持纵横比缩放图片,使图片的长边能完全显示出来。也就是说,可以完整地将图片显示出来。
	
mode="aspectFill"
	保持纵横比缩放图片,只保证图片的短边能完全显示出来。也就是说,图片通常只在水平或垂直方向是完整的,另一个方向将会发生截取。

mode="scaleToFill"
	不保持纵横比缩放图片,使图片的宽高完全拉伸至填满 image 元素

mode="widthFix"
	宽度不变,高度自动变化,保持原图宽高比不变

6:合理的设置变量,关键是会使用style class 来写三元表达式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章