识别本地图片的方法有哪些?

识别本地图片的方法

HarmonyOS
2024-08-07 09:21:17
858浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
xiaohur
// DetectBarcode.ets 通过picker选取图片进行图片识码
import { image } from '@kit.ImageKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { picker, fileIo } from '@kit.CoreFileKit';
import { router, promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
import { scanCore, detectBarcode, scanBarcode } from '@kit.ScanKit';

const TAG = 'ScanKit detectBarcode';

@Entry
@Component
struct DetectBarcodePage {
  build() {
    Column() {
      Button('识别本地图片')
        .backgroundColor($r('sys.color.ohos_id_color_button_normal'))
        .fontColor($r('sys.color.ohos_id_color_text_primary_activated'))
        .align(Alignment.Center)
        .type(ButtonType.Capsule)
        .margin({ bottom: 12 })
        .width('90%')
        .height(40)
        .onClick(() => {
          // 定义扫码参数options,图片识码设置扫码参数
          let options: scanBarcode.ScanOptions = {
            scanTypes: [scanCore.ScanType.ALL],
            enableMultiMode: true // 单码识别false,多码识别true
          }
          try {
            // 通过picker拉起图库的图片
            let photoOption = new picker.PhotoSelectOptions();
            photoOption.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
            photoOption.maxSelectNumber = 1;
            let photoPicker = new picker.PhotoViewPicker();
            photoPicker.select(photoOption).then((photoResult) => {
              let infoW: number = 0;
              let infoH: number = 0;
              try {
                let file = fileIo.openSync(photoResult.photoUris[0], fileIo.OpenMode.READ_ONLY);
                const imageSourceApi = image.createImageSource(file.fd);
                imageSourceApi.getImageInfo(0, (error: BusinessError, imageInfo) => {
                  if (imageInfo == undefined) {
                    hilog.error(0x0001, TAG,
                      `Failed to get imageInfo by callbak. Code: ${error.code}, message: ${error.message}`);
                    return;
                  }
                  infoW = imageInfo.size.width;
                  infoH = imageInfo.size.height;
                })
              } catch (error) {
                hilog.error(0x0001, TAG, `Failed to get imageInfo. Code: ${error.code}, message: ${error.message}`);
                return;
              }
              try {
                // 定义扫码参数inputImage,其中uri为picker选择图片
                let inputImage: detectBarcode.InputImage = { uri: photoResult.photoUris[0] }
                // 调用图片识码接口,为promise带参数的接口形式
                detectBarcode.decode(inputImage, options).then((result: Array<scanBarcode.ScanResult>) => {
                  hilog.info(0x0001, TAG,
                    `Succeeded in getting ScanResult by promise with options, result is ${JSON.stringify(result)}`);
                  if (result && result.length > 0) {
                    router.pushUrl({
                      url: 'pages/ResultPage',
                      params: {
                        result: result,
                        uri: photoResult.photoUris[0],
                        infoW: infoW,
                        infoH: infoH,
                        options: options
                      }
                    })
                  } else {
                    promptAction.showToast({
                      message: '未识别到二维码/条形码。',
                      duration: 2000
                    });
                  }
                }).catch((error: BusinessError) => {
                  if (photoResult.photoUris[0]) {
                    promptAction.showToast({
                      message: '未识别到二维码/条形码。',
                      duration: 2000
                    });
                    hilog.error(0x0001, TAG,
                      `Failed to get ScanResult by promise with options. Code: ${error.code}, message: ${error.message}`);
                  }
                });
              } catch (error) {
                hilog.error(0x0001, TAG, `Failed to decode. Code: ${error.code}, message: ${error.message}`);
              }
            })
          } catch (error) {
            hilog.error(0x0001, TAG, `Failed to select photo. Code: ${error.code}, message: ${error.message}`);
          }
        });
    }
    .width('100%')
    .height('100%')
    .alignItems(HorizontalAlign.Center)
    .justifyContent(FlexAlign.Center)
  }
}

// ResultPage.ets 展示图片识码的结果,以及绘制码图的位置
import { hilog } from '@kit.PerformanceAnalysisKit';
import { scanBarcode } from '@kit.ScanKit';
import { display, router } from '@kit.ArkUI';

const TAG: string = 'ScanKit scanResult';
let typeStr: Array<string> =
  ['FORMAT_UNKNOWN', 'AZTEC_CODE', 'CODABAR_CODE', 'CODE39_CODE', 'CODE93_CODE', 'CODE128_CODE', 'DATAMATRIX_CODE',
    'EAN8_CODE', 'EAN13_CODE',
    'ITF14_CODE', 'PDF417_CODE', 'QR_CODE', 'UPC_A_CODE', 'UPC_E_CODE', ''];

@Entry
@Component
struct ScanResultPage {
  private result: Array<scanBarcode.ScanResult> = [];
  private uri: string = ''
  private infoW: number = 0
  private infoH: number = 0
  @State cameraHeight: number = 1412
  @State cameraWidth: number = 720
  @State layTop: number = 226
  @State layLeft: number = 0
  @State screen: number = 1
  @State rx: number = 0
  @State ry: number = 0
  @State rw: number = 0
  @State rh: number = 0
  public scroller: Scroller = new Scroller()
  private statusHeight: number = 39

  aboutToAppear() {
    let isFold: boolean = display.isFoldable();
    this.setDisplay();
    hilog.info(0x0001, TAG, 'aboutToAppear ResultPage');
    let params = router.getParams() as Record<string, number | string | Array<scanBarcode.ScanResult>>;
    // 识别码图返回结果
    this.result = params.result as Array<scanBarcode.ScanResult>;
    this.uri = params.uri as string;
    this.infoW = params.infoW as number;
    this.infoH = params.infoH as number;
    hilog.info(0x0001, TAG, `Succeeded in getting params: ${JSON.stringify(params)}`);
    hilog.info(0x0001, TAG, `Succeeded in getting result: ${JSON.stringify(this.result)}`);
    hilog.info(0x0001, TAG,
      `Succeeded in getting uri: ${this.uri}, this.infoW: ${this.infoW}, this.infoH: ${this.infoH}`);
    this.calculate();
    if (isFold) {
      display.on('foldStatusChange', async (foldStatus: display.FoldStatus) => {
        // 1:展开态,2:折叠态
        if (foldStatus === 1 || foldStatus === 2) {
          setTimeout(() => {
            this.setDisplay();
            this.calculate();
          }, 300)
        }
      });
    }
  }

  setDisplay(): void {
    hilog.info(0x0001, TAG, 'setDisplay start');
    let displayClass: display.Display | null = null;
    try {
      displayClass = display.getDefaultDisplaySync();
      hilog.info(0x0001, TAG, `Succeeded in getting displayClass: ${JSON.stringify(displayClass)}`);
    } catch (exception) {
      hilog.error(0x0001, TAG, `Failed to get displayClass. Code: ${exception.code}, message: ${exception.message}`);
    }

    if (displayClass !== null) {
      displayClass.height = displayClass.height - vp2px(this.statusHeight);
      this.cameraHeight = Math.round(px2lpx(displayClass.height));
      this.cameraWidth = Math.round(px2lpx(displayClass.width));
      hilog.info(0x0001, TAG, `Succeeded in getting cameraHeight: ${this.cameraHeight}`);
      hilog.info(0x0001, TAG, `Succeeded in getting cameraWidth: ${this.cameraWidth}`);
    }
  }

  calculate() {
    // 计算当前图片宽高和屏幕宽高的比例换算
    if (this.infoW && this.infoH && this.cameraHeight && this.cameraWidth) {
      if (this.infoW / this.infoH > this.cameraWidth / this.cameraHeight) {
        this.screen = 720 / this.infoW;
        this.layTop = (this.cameraHeight - this.cameraWidth * this.infoH / this.infoW) / 2;
        this.layLeft = 0;
      } else {
        this.layTop = 0;
        this.layLeft = (this.cameraWidth - this.cameraHeight * this.infoW / this.infoH) / 2;
        this.screen = this.cameraHeight / this.infoH;
      }
    }
  }

  @Builder
  CustomTextBox(scanType: string, inputValue: string, left: number, top: number, right: number, bottom: number) {
    Column() {
      Column() {
        Text('码类型')
        Text(scanType).align(Alignment.Start)
      }
      .width('100%')
      .justifyContent(FlexAlign.Start)
      .alignItems(HorizontalAlign.Start)
      .margin({ top: 10 })

      Column() {
        Text('码值')
        Text(inputValue)
      }.width('100%').justifyContent(FlexAlign.Start)
      .alignItems(HorizontalAlign.Start)
      .margin({ top: 10 })

      Column() {

        Text('码位置信息').align(Alignment.Start)
        Text('left: ' + left + '  top: ' + top + '  right: ' + right + '  bottom: ' + bottom).align(Alignment.Start)
      }.width('100%').justifyContent(FlexAlign.Start)
      .alignItems(HorizontalAlign.Start)
      .margin({ top: 10 })

    }.margin({ bottom: 5 })
  }

  build() {
    Stack() {
      // 显示码图
      Image(this.uri)
        .objectFit(ImageFit.Contain)
        .width('100%').height('100%')
      // 判断二维码返回数据,显示位置
      ForEach(this.result, (item: scanBarcode.ScanResult, index: number) => {
        Column() {
          if (item.scanCodeRect && index >= 0) {
            Image($rawfile('scan_selected.svg'))
              .width(40)
              .height(40)
              .markAnchor({ x: 20, y: 20 })
              .position({
                x: Math.round(item.scanCodeRect.left * this.screen + this.layLeft) +
                  Math.round((item.scanCodeRect.right - item.scanCodeRect.left) * this.screen) / 2 + 'lpx',
                y: Math.round(item.scanCodeRect.top * this.screen + this.layTop) +
                  Math.round((item.scanCodeRect.bottom - item.scanCodeRect.top) * this.screen) / 2 + 'lpx',
              })
          }
        }.width('100%')
        .height('100%')
      })

      Scroll(this.scroller) {
        Column() {
          Image($rawfile('scan_back.svg'))
            .fillColor(Color.Black)
            .width(30)
            .height(30)
            .objectFit(ImageFit.Contain)
            .position({ x: 0, y: 0 })
            .zIndex(10)
            .onClick(async () => {
              router.back();
            })
          Column() {
            Text('结果')
              .fontSize(18)
              .fontColor('#000000')
              .margin({ top: 20 })
            ForEach(this.result, (item: scanBarcode.ScanResult) => {
              if (item['scanCodeRect']) {
                this.CustomTextBox(typeStr[item['scanType']], item['originalValue'], item['scanCodeRect']['left'],
                  item['scanCodeRect'].top, item['scanCodeRect'].right, item['scanCodeRect'].bottom)
              }
            })
          }
          .width('80%')
          .height('100%')
        }
      }
      .scrollable(ScrollDirection.Vertical)
      .scrollBar(BarState.On)
      .scrollBarColor(Color.Gray)
      .scrollBarWidth(5)
      .height('100%')
    }
    .width('100%')
    .height('100%')
    .padding({
      top: 40
    })
  }
}
  • 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.
分享
微博
QQ
微信
回复
2024-08-07 11:30:41


相关问题
语音识别方法哪些
1406浏览 • 1回复 待解决
如何获取手机本地图片
1046浏览 • 1回复 待解决
HarmonyOS 如何压缩本地图片
831浏览 • 1回复 待解决
HarmonyOS customScan 如何扫描本地图片
690浏览 • 1回复 待解决
HarmonyOS 如何上传本地图片
825浏览 • 1回复 待解决
HarmonyOS Image加载本地图片咨询
1314浏览 • 1回复 待解决
HarmonyOS Image展示本地图片失败
1177浏览 • 1回复 待解决
HarmonyOS如何获取手机本地图片
1339浏览 • 1回复 待解决
HarmonyOS 卡片使用本地图片作为背景
598浏览 • 1回复 待解决
服务卡片设置本地图片显示空白
8394浏览 • 2回复 已解决
如何保存本地图片到相册中
2173浏览 • 1回复 待解决
ArkUI(eTS)如何实现本地图片保存?
8236浏览 • 1回复 待解决
HarmonyOS 本地图库选择器并编辑图片
742浏览 • 1回复 待解决
文本转语音方法哪些?
1147浏览 • 1回复 待解决
Greenplum哪些通用处理方法
4296浏览 • 1回复 待解决