ocrUsedCarModules.js 11.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
// components/OcrPhoto.js
import { getSystemInfoSync } from '~/utils/systemInfo'
import newApi from "~/packageUsedCar/api";
import api from "~/api/api";
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",
    tips: {
      standNo: "请扫描车辆车架号,拍照识别",
      plateNumber: "请扫描车辆前后方车牌拍照,拍照识别",
    },
    typeClass: "standNo",
    isPageActive: true
  },
  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 that = this;
    let { canvas, ctx, windowWidth, windowHeight, iPath } = this.data;
    windowWidth = windowWidth;
    windowHeight = windowHeight;
    wx.$util.showLoading("生成中...");
    console.log(windowWidth, windowHeight);

    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)

      //截取图片指定部分并绘制到canvas
      ctx.drawImage(img, 0, 0, windowWidth, windowHeight);
      // wx.$util.showToast('img属性')
      //绘制图片
      // ctx.draw()

      setTimeout(() => {
        //将canvas内容保存为图片
        wx.canvasToTempFilePath({
          canvas: canvas,
          // x: c_x,
          // y: c_y,
          // width: c_w,
          // height: c_h,
          // destWidth: c_w,
          // destHeight: c_h,
          fileType: "jpg",
          quality: 1, // 图片质量
          success: (res) => {
            wx.$util.hideLoading();
            //将图片保存到本地相册
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success(res) {
                // wx.$util.showToast('已将图片保存到本地相册', res)
              },
              fail(err) {
                wx.$util.showToast("失败", err);
                console.log(err);
              },
            });
            that.uploadImg(res.tempFilePath, "png");
          },
          fail: (res) => {
            wx.$util.hideLoading();
            console.log(res);
          },
        });
      }, 500);
    };
    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);
        wx.$util.showLoading("上传中...");
        api
          .uploadImg({
            file: `${type}@${_res.data}`,
          })
          .then((img) => {
            wx.$util.hideLoading();
            let { code, data, message } = img;
            if (code == 0) {
              that.orcRecogintion(data);
            } else {
              wx.$util.showToast(message);
            }
          });
      },
    });
  },

  orcRecogintion(url) {
    let { typeClass } = this.data;
    // 根据类型选择不同的 API
    wx.$util.showLoading("识别中...");
    const apiCall =
      typeClass === "vin"
        ? newApi.vinOcr({ imageUrl: url })
        : newApi.carLicenseOcr({ imageUrl: url });

    apiCall
      .then((result) => {
        wx.$util.hideLoading();
        console.log("ocr", result);
        let { code, data } = result.data;
        console.log(data && data.status == 0, "data");
        if (this.data.isPageActive) { // 添加页面存活标识符, 防止识别接口未返回前,操作了返回页面,出现返回后接口调用成功再次触发返回
          if (code == 0 && data && data.status == 1) {
            wx.$router.back((page) => {
              page.reWrite && page.reWrite(typeClass, data);
            });
          } else {
            console.log("识别失败");
            setTimeout(() => {
              wx.$util.showToast(
                {
                  title: "识别失败请重试",
                  icon: "fail",
                  // duration: 2000,//提示的延迟时间,单位毫秒,默认:1500
                },
                500
              );
            });
          }
        }
      })
      .catch((err) => {
        console.log(err);
        wx.$util.hideLoading();
      })
      .finally((res) => {
        wx.$util.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("实例化");
    this.setData({ isPageActive: true })
    if (data) {
      this.setData({
        typeClass: data.type,
      });

      // 根据不同类型设置导航栏标题
      let title = "识别";
      if (data.type === "licensePlate") {
        title = "行驶证识别";
      } else if (data.type === "vin") {
        title = "车架号识别";
      } else if (data.type === "idCard") {
        title = "身份证识别";
      }

      wx.setNavigationBarTitle({
        title: title,
      });
    }
    //   // 在组件实例进入页面节点树时执行
    var that = this;
    that.ctx = wx.createCameraContext();
    let { windowWidth, windowHeight } = getSystemInfoSync();
    this.setData({ windowWidth, windowHeight });
    setTimeout(() => {
      that.initCanvas();
    }, 100);
  },
  initCanvas() {
    console.log("onReady");
    try {
      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 });
        });
    } catch (error) {
      console.log(error);
    }
  },
  // 在页面首次渲染实现生命周期获取操作canvas的上下文对象
  onReady() {},
  onUnload() {
    this.setData({ isPageActive: false })
  }
});