鴻蒙專案實戰(六):識別本地圖片

听着music睡發表於2024-11-18

基本概念

圖片識碼能力支援對相簿中的碼圖進行掃描識別,並獲取資訊

場景介紹

圖片識碼能力支援對相簿中的條形碼、二維碼、MULTIFUNCTIONAL CODE進行識別,並獲得碼型別、碼值、碼位置資訊

該能力可用於一圖單碼和一圖多碼的識別,比如條形碼、付款碼等

使用示例

1、匯入圖片識碼介面和相關介面模組

import { scanCore, scanBarcode, detectBarcode } from '@kit.ScanKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

2、呼叫detectBarcode.decode介面解析碼圖。

  • 透過Promise回撥函式得到掃碼結果,InputImage物件中uri引數推薦透過picker方式獲取
// 匯入圖片識碼需要的日誌和picker模組
import { scanCore, scanBarcode, detectBarcode } from '@kit.ScanKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct MainPage {
  pageInfo: NavPathStack = new NavPathStack()
  // 選擇並識別本地圖片內容
  chooseLocalPicAndScan(){
    // 定義識碼引數options
    let options: scanBarcode.ScanOptions = {
      scanTypes: [scanCore.ScanType.ALL], // 識別的barcode型別
      enableMultiMode: true,
    }
    // 透過picker拉起相簿的圖片
    let photoOption = new photoAccessHelper.PhotoSelectOptions();
    photoOption.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
    photoOption.maxSelectNumber = 1; // 最大選擇圖片數量
    let photoPicker = new photoAccessHelper.PhotoViewPicker();
    photoPicker.select(photoOption).then((result) => {
      // 定義識碼引數inputImage,其中uri為picker選擇圖片
      let inputImage: detectBarcode.InputImage = { uri: result.photoUris[0] };
      try {
        // 呼叫圖片識碼介面
        detectBarcode.decode(inputImage, options).then((result: Array<scanBarcode.ScanResult>) => {
          hilog.info(0x0001, '[Scan Sample]',
            `Succeeded in getting ScanResult by promise with options, result is ${JSON.stringify(result)}`);
        }).catch((error: BusinessError) => {
          hilog.error(0x0001, '[Scan Sample]',
            `Failed to get ScanResult by promise with options. Code: ${error.code}, message: ${error.message}`);
        });
      } catch (error) {
        hilog.error(0x0001, '[Scan Sample]',
          `Failed to detectBarcode. Code: ${error.code}, message: ${error.message}`);
      }
    })
  }
  build() {
    Navigation(this.pageInfo) {
      Column() {
        Button('識別本地圖片')
          .onClick(()=>{
              this.chooseLocalPicAndScan()
          })
          .margin(10)
      }
      .width('100%')
    }
    .height('100%')
  }
}
  • 透過Callback回撥函式得到掃碼結果,InputImage物件中uri引數推薦透過picker方式獲取
// 啟動頁
// 匯入圖片識碼需要的日誌和picker模組
import { scanCore, scanBarcode, detectBarcode } from '@kit.ScanKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct MainPage {
  pageInfo: NavPathStack = new NavPathStack()

  // 選擇並識別本地圖片內容
  chooseLocalPicAndScan() {
    // 定義識碼引數options
    let options: scanBarcode.ScanOptions = {
      scanTypes: [scanCore.ScanType.ALL],
      enableMultiMode: true,
      enableAlbum: true
    }
    // 透過選擇模式拉起photoPicker介面,使用者可以選擇一個圖片
    let photoOption = new photoAccessHelper.PhotoSelectOptions();
    photoOption.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
    photoOption.maxSelectNumber = 1;
    let photoPicker = new photoAccessHelper.PhotoViewPicker();
    photoPicker.select(photoOption).then((result) => {
      // 定義識碼引數inputImage,其中uri為picker選擇圖片
      let inputImage: detectBarcode.InputImage = { uri: result.photoUris[0] };
      try {
        // 呼叫圖片識碼介面
        detectBarcode.decode(inputImage, options,
          (error: BusinessError, result: Array<scanBarcode.ScanResult>) => {
            if (error && error.code) {
              hilog.error(0x0001, '[Scan Sample]',
                `Failed to get ScanResult by callback with options. Code: ${error.code}, message: ${error.message}`);
              return;
            }
            hilog.info(0x0001, '[Scan Sample]',
              `Succeeded in getting ScanResult by callback with options, result is ${JSON.stringify(result)}`);
          });
      } catch (error) {
        hilog.error(0x0001, '[Scan Sample]',
          `Failed to detectBarcode. Code: ${error.code}, message: ${error.message}`);
      }
    })
  }


  build() {
    Navigation(this.pageInfo) {
      Column() {
        Text('首頁')
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        Button('跳轉第一頁')
          .onClick(() => {
            this.pageInfo.pushPathByName("FirstPage", null)
          })
          .margin({ top: 100 })
        Button('跳轉第二頁')
          .onClick(() => {
            this.pageInfo.pushPathByName("SecondPage", null)
          })
          .margin(10)
        Button('識別本地圖片')
          .onClick(() => {
            this.chooseLocalPicAndScan()
          })
          .margin(10)
      }
      .width('100%')
    }
    .height('100%')
  }
}

相關文件:

識別本地圖片

相關文章