HarmonyOS 如何识别网络图片的二维码信息

HarmonyOS
2025-01-10 07:59:08
7653浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
fox280
  1. Scan Kit有提供“识别本地图片”的功能;此功能需要接入方应用调用detectBarcode.decode方法并传入待识别图片的uri即可;

<a name="table16204122673316"></a> <table><thead align="left"><tr id="row1122362663310"><th class="cellrowborder" valign="top" width="50%" id="mcps1.1.3.1.1"><p id="p52232263333"><a name="p52232263333"></a><a name="p52232263333"></a>接口名</p> </th> <th class="cellrowborder" valign="top" width="50%" id="mcps1.1.3.1.2"><p id="p19223102603318"><a name="p19223102603318"></a><a name="p19223102603318"></a>描述</p> </th> </tr> </thead> <tbody><tr id="row172231626153319"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.1 "><p id="p1422332663320"><a name="p1422332663320"></a><a name="p1422332663320"></a><a href="https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/scan-imagedecode-V5#section9221156204617" target="_blank" rel="noopener noreferrer">decode</a>(inputImage: <a href="https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/scan-imagedecode-V5#section2194164873812" target="_blank" rel="noopener noreferrer">InputImage</a>, options?: scanBarcode.<a href="https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/scan-scanbarcode-api-V5#section1285191073117" target="_blank" rel="noopener noreferrer">ScanOptions</a>): Promise<Array<scanBarcode.<a href="https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/scan-scanbarcode-api-V5#section10614317162112" target="_blank" rel="noopener noreferrer">ScanResult</a>>></p> </td> <td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.2 "><p id="p1722312611336"><a name="p1722312611336"></a><a name="p1722312611336"></a>启动图片识码,通过InputImage传入图片信息,通过ScanOptions进行识码参数设置(options为可选参数),使用Promise异步回调返回识码结果。</p> </td> </tr> <tr id="row15223426183314"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.1 "><p id="p9223226153317"><a name="p9223226153317"></a><a name="p9223226153317"></a><a href="https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/scan-imagedecode-V5#section12482559194718" target="_blank" rel="noopener noreferrer">decode</a>(inputImage: InputImage, options: scanBarcode.ScanOptions, callback: AsyncCallback<Array<scanBarcode.ScanResult>>): void</p> </td> <td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.2 "><p id="p19223192603310"><a name="p19223192603310"></a><a name="p19223192603310"></a>启动图片识码,通过InputImage传入图片信息,通过ScanOptions进行识码参数设置,使用Callback异步回调返回识码结果。</p> </td> </tr> <tr id="row922332611337"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.1 "><p id="p122231526113310"><a name="p122231526113310"></a><a name="p122231526113310"></a><a href="https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/scan-imagedecode-V5#section17256144317492" target="_blank" rel="noopener noreferrer">decode</a>(inputImage: InputImage, callback: AsyncCallback<Array<scanBarcode.ScanResult>>): void</p> </td> <td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.2 "><p id="p6223172683315"><a name="p6223172683315"></a><a name="p6223172683315"></a>启动图片识码,通过InputImage传入图片信息,使用Callback异步回调返回识码结果。</p> </td> </tr> </tbody> </table>

  1. 基于第一点,实现此功能可以分为三个步骤,分别是:

a. 应用可以先将图片下载到本地并保存到沙箱;

b. 获取到保存到沙箱的图片uri;

c. 使用“识别本地图片”能力识别图片二维码即可;

参考代码如下:

import { scanCore, scanBarcode, detectBarcode } from '@kit.ScanKit';
// 导入功能涉及的权限申请、回调接口
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { image } from '@kit.ImageKit';
import { http } from '@kit.NetworkKit';
import { common } from '@kit.AbilityKit';
import { fileIo as fs, fileUri } from '@kit.CoreFileKit';

@Entry
@Component
struct ScanBarCodePage {
  @State pixelMap: image.PixelMap | string | undefined = undefined
  @State scanResult: string = ''

  loadImageWithUrl(url: string) {
    try {
      // 使用request下载图片并在回调函数中保存图片到相册
      http.createHttp().request(url,
        {
          method: http.RequestMethod.GET,
          connectTimeout: 60000,
          readTimeout: 60000
        }, (error: BusinessError, data: http.HttpResponse) => {
          this.loadImageCallback(error, data);
        })
    } catch (e) {
      console.log(`testTAG ====== e:${e}`);
    }
  }

  //下载图片的回调函数
  async loadImageCallback(error: BusinessError, data: http.HttpResponse) {
    if (http.ResponseCode.OK === data.responseCode) {
      let imageBuffer: ArrayBuffer = data.result as ArrayBuffer;
      this.saveImage(imageBuffer)
    } else {
      console.error("testTAG==error occurred when image downloaded!")
    }
  }

  //保存图片至沙箱
  async saveImage(imageBuffer: ArrayBuffer) {
    // 获取应用文件路径
    let context = getContext(this) as common.UIAbilityContext;
    let filesDir = context.filesDir;
    // 新建并打开文件
    let file = fs.openSync(filesDir + '/testimage.jpg', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    // 写入一段内容至文件
    fs.writeSync(file.fd, imageBuffer);
    //获取已存在沙箱的图片uri
    const imageUri = fileUri.getUriFromPath(filesDir + '/testimage.jpg')
    this.pixelMap = imageUri
    console.log(`testTAG: imageUri` + imageUri);
    // 关闭文件
    fs.closeSync(file);
    let options: scanBarcode.ScanOptions = {
      scanTypes: [scanCore.ScanType.ALL],
      enableMultiMode: true,
    }
    //进行码图识别
    let inputImage: detectBarcode.InputImage = { uri: imageUri }
    // 调用图片识码接口
    detectBarcode.decode(inputImage, options).then((result: Array<scanBarcode.ScanResult>) => {
      hilog.info(0x0001, 'testTAG',
        `Succeeded in getting ScanResult by promise with options, result is ${JSON.stringify(result)}`);
      this.scanResult = JSON.stringify(result)
    }).catch((error: BusinessError) => {
      hilog.error(0x0001, 'testTAG',
        `Failed to get ScanResult by promise with options. Code: ${error.code}, message: ${error.message}`);
    });
  }

  build() {
    Column() {
      Button('识别网络图像数据').onClick(() => {
        this.loadImageWithUrl("https://example.com")
      })
      Text(this.scanResult)
      // 获取生成码后显示
      if (this.pixelMap) {
        Image(this.pixelMap).width(300).height(300).objectFit(ImageFit.Contain)
      }
    }
    .backgroundColor('#DDDDDD')
    .width('100%')
    .height('100%')
  }
}
  • 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.
分享
微博
QQ
微信
回复
2025-01-10 11:18:52
相关问题
HarmonyOS 二维条码扫描识别
1310浏览 • 1回复 待解决
HarmonyOS 二维生成失败
764浏览 • 1回复 待解决
HarmonyOS zxing二维
958浏览 • 1回复 待解决
HarmonyOS如何无感知扫描二维
1149浏览 • 1回复 待解决
HarmonyOS 二维生成demo
1127浏览 • 2回复 待解决
HarmonyOS 支持扫描二维吗?
1147浏览 • 1回复 待解决
HarmonyOS扫描二维方案是什么?
2985浏览 • 1回复 待解决
HarmonyOS APP可以生成二维,扫安装
1549浏览 • 1回复 待解决
二维扫描三方库推荐
929浏览 • 1回复 待解决
HarmonyOS h5加载二维屏幕变亮
820浏览 • 1回复 待解决
Canvas组件实现二维中心内嵌图标
1551浏览 • 1回复 待解决