ocr.js 10.8 KB
// components/OcrPhoto.js
import api from '~/api/api.js'
import { getSystemInfoSync } from '~/utils/systemInfo'
Page({
  /**
   * 组件的属性列表
   */
  properties: {},

  /**
   * 组件的初始数据
   */
  data: {
    isShowImage: true,
    isAuth: false,
    isPhotos: false,
    windowWidth: '',
    windowHeight: '',
    canvas: '',
    ctx: '',
    iPath: '',

    cameraBtnSrc: './image/cameraBtn.png',
    picUploadSrc: './image/picPick.png',
    bgSrc: './image/backGroundImage.png',
    // type: 'vin',
    tips: {
      standNo: '请扫描车辆车架号,拍照识别',
      plateNumber: '请扫描车辆前后方车牌拍照,拍照识别'
    },
    typeClass: 'standNo',
    type: {
      standNo: 3,
      plateNumber: 4
    }
  },
  takePhoto: function () {
    var that = this
    // wx.$util.showToast('takePhoto', that.ctx)
    that.ctx.takePhoto({
      quality: 'high',
      success: res => {
        // that.loadTempImagePath(res.tempImagePath)
        this.setData({
          iPath: res.tempImagePath
        })
        // ctx2, canvas
        this.initImg()
      },
      fail: error => {
        console.log(error)
      },
      complete: res => {
        console.log(res)
      }
    })
  },

  initImg(imgUrl) {
    let { canvas, ctx, windowWidth, windowHeight, iPath } = this.data

    canvas.width = windowWidth
    canvas.height = windowHeight

    let img = canvas.createImage()
    img.src = iPath

    img.onload = () => {
      let c_x = windowWidth * (60 / 750)
      let c_y = windowHeight * (160 / 1200)
      let c_w = windowWidth * (680 / 750)
      let c_h = windowHeight * (260 / 1200)
      // wx.$util.showToast(img.width, imgheight)

      //截取图片指定部分并绘制到canvas
      ctx.drawImage(img, 0, 0, windowWidth, windowHeight)
      // wx.$util.showToast('img属性')
      //将canvas内容保存为图片
      wx.canvasToTempFilePath({
        canvas: canvas,
        x: c_x,
        y: c_y,
        width: c_w,
        height: c_h,
        destWidth: c_w,
        destHeight: c_h,
        fileType: 'png',
        quality: 1, // 图片质量
        success: res => {
          //将图片保存到本地相册
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(res) {
              // wx.$util.showToast('已将图片保存到本地相册', res)
            },
            fail(err) {
              wx.$util.showToast('失败', err)
              console.log(err)
            }
          })
          this.uploadImg(res.tempFilePath, 'png')
        },
        fail: res => {
          console.log(res)
        }
      })
    }
    img.onerror = e => {
      console.error('err:', e)
    }
  },

  // 上传图片
  uploadImg(url, type) {
    let that = this
    // let [tempFiles] = res.tempFilePaths
    // let imgType = tempFiles.split('.')[1]
    // let type = imgType == 'unknown' ? 'jpg' : imgType
    wx.$util.showLoading('识别中...')
    wx.getFileSystemManager().readFile({
      filePath: url, //选择图片返回的相对路径
      encoding: 'base64', //编码格式
      success(_res) {
        console.log(_res)
        that.orcRecogintion(_res.data)
        // return
        // api
        //   .uploadImg({
        //     file: `${type}@${_res.data}`
        //   })
        //   .then(img => {
        //     // wx.$util.hideLoading()
        //     // console.log(img)
        //     let { code, data, message } = img
        //     if (code == 0) {
        //       // 调用ocr接口识别
        //       console.log(data)
        //       that.orcRecogintion(data)
        //       // _this.setData({
        //       //   payVoucher: data
        //       // })
        //     } else {
        //       wx.$util.showToast(message)
        //     }
        //   })
      }
    })
  },

  orcRecogintion(base64) {
    let { typeClass, type } = this.data
    api
      .ocr({ type: type[typeClass], imgBase64: base64 })
      .then(result => {
        wx.hideLoading()
        // console.log('ocr', result)
        let { code, data } = result
        let ocrType = {
          standNo: 'vin',
          plateNumber: 'licensePlateNum'
        }
        // console.log(data[ocrType[typeClass]])
        if (code == 0 && data && data[ocrType[typeClass]]) {
          // let { type } = this.data
          // licensePlateNum: "粤X83338"
          // vin: "LSGGF53W8CH045613"

          wx.$router.back(page => {
            page.reWrite && page.reWrite(typeClass, data[ocrType[typeClass]])
          })
        } else {
          console.log('识别失败')
          setTimeout(() => {
            wx.$util.showToast(
              {
                title: '识别失败请重试',
                icon: 'fail'
                // duration: 2000,//提示的延迟时间,单位毫秒,默认:1500
              },
              500
            )
          })
        }
      })
      .catch(err => {
        console.log(err)
      })
      .finally(res => {
        wx.hideLoading()
      })
  },

  choseImg() {
    let _this = this
    wx.chooseImage({
      count: 1,
      success(res) {
        let [tempFiles] = res.tempFilePaths
        let imgType = tempFiles.split('.')[1]
        let type = imgType == 'unknown' ? 'jpg' : imgType
        _this.uploadImg(tempFiles, type)
      }
    })
  },

  //  获取摄像头授权
  getCameraSetting() {
    // console.log('获取权限')
    let _this = this
    return new Promise((reslove, reject) => {
      wx.authorize({
        scope: 'scope.camera',
        success() {
          console.log('用户同意授权')
          // 用户同意授权
          _this.setData({
            isAuth: true
            // isNeedSettingButton: false
          })
          reslove(true)
        },
        fail() {
          // 用户不同意授权
          wx.showModal({
            title: '提示',
            content: '如需正常使用此小程序功能,请您按确定并在设置页面授权用户信息',
            cancelText: '不授权',
            cancelColor: '#999',
            confirmText: '授权',
            //   confirmColor: '#f94218',
            success(res) {
              if (res.confirm) {
                wx.openSetting({
                  success(res) {
                    if (res.authSetting['scope.camera']) {
                      //设置允许获取摄像头
                      console.log('设置允许获取摄像头')
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      _this.setData({
                        isAuth: true
                      })
                      reslove(true)
                    } else {
                      //不允许
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                      reject(false)
                      wx.$router.back()
                    }
                  }
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
                wx.showToast({
                  title: '授权失败',
                  icon: 'none',
                  duration: 1000
                })
                reject(false)
                wx.$router.back()
              }
            }
          })
        }
      })
    })
  },

  //  获取存图片授权
  getWritePhotosSetting() {
    // console.log('获取权限')
    let _this = this
    // return new Promise((reslove, reject) => {
    wx.authorize({
      scope: 'scope.writePhotosAlbum',
      success() {
        console.log('用户同意授权')
        // 用户同意授权
        _this.setData({
          isPhotos: true
          // isNeedSettingButton: false
        })
        // reslove(true)
      },
      fail() {
        // 用户不同意授权
        wx.showModal({
          title: '提示',
          content: '如需正常使用此小程序功能,请您按确定并在设置页面授权用户信息',
          cancelText: '不授权',
          cancelColor: '#999',
          confirmText: '授权',
          //   confirmColor: '#f94218',
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                success(res) {
                  if (res.authSetting['scope.camera']) {
                    //设置允许获取摄像头
                    console.log('设置允许保存图片')
                    wx.showToast({
                      title: '授权成功',
                      icon: 'success',
                      duration: 1000
                    })
                    _this.setData({
                      isPhotos: true
                    })
                    // reslove(true)
                  } else {
                    //不允许
                    wx.showToast({
                      title: '授权失败',
                      icon: 'none',
                      duration: 1000
                    })
                    // reject(false)
                    wx.$router.back()
                  }
                }
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
              wx.showToast({
                title: '授权失败',
                icon: 'none',
                duration: 1000
              })
              // reject(false)
              wx.$router.back()
            }
          }
        })
      }
    })
  },

  onShow: function (data) {
    // console.log(data)
    console.log('调用权限')
    let { isAuth } = this.data
    // !isAuth && this.getCameraSetting()
    this.getCameraSetting()
      .then(result => {
        console.log(result)

        result && this.getWritePhotosSetting()
      })
      .catch(err => {
        console.log(err)
      })
  },
  onLoad: function (data) {
    // console.log('调用权限')
    // console.log(data)
    console.log('实例化')

    if (data) {
      this.setData({
        typeClass: data.type
      })
      wx.setNavigationBarTitle({
        title: data.type == 'standNo' ? '车架号识别' : '车牌识别'
      })
      wx.$util.pointRecord(data.type == 'standNo'?20:21)
    }
    //   // 在组件实例进入页面节点树时执行
    var that = this
    that.ctx = wx.createCameraContext()
    let { windowWidth, windowHeight } = getSystemInfoSync()
    this.setData({ windowWidth, windowHeight })
  },
  // 在页面首次渲染实现生命周期获取操作canvas的上下文对象
  onReady() {
    const query = wx.createSelectorQuery()
    query
      .select('#image-canvas')
      .fields({ node: true, size: true })
      .exec(res => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        console.log(canvas, ctx, 'canvas, ctx')
        this.setData({ canvas, ctx })
      })
  }
})