HarmonyOS-鸿蒙app开发 —基于javaAI码生成开发指导

HarmonyOS-鸿蒙app开发 —基于javaAI码生成开发指导

场景介绍

码生成能够根据给定的字符串信息,生成相应的二维码图片。常见应用场景举例:

  • 社交或通讯类应用:根据输入的联系人信息,生成联系人二维码。
  • 购物或支付类应用:根据输入的支付链接,生成收款或付款二维码。

接口说明

码生成提供了IBarcodeDetector()接口,常用方法的功能描述如下:

接口名

方法

功能描述

IBarcodeDetector

int detect(String barcodeInput, byte[] bitmapOutput, int width, int height);

根据给定的信息和二维码图片尺寸,生成二维码图片字节流。

IBarcodeDetector

int release();

停止QR码生成服务,释放资源。

开发步骤

  1. 在使用码生成SDK时,需要先将相关的类添加至工程。

import ohos.ai.cv.common.ConnectionCallback;
import ohos.ai.cv.common.VisionManager;
import ohos.ai.cv.qrcode.IBarcodeDetector;

定义ConnectionCallback回调,实现连接能力引擎成功与否后的操作。

ConnectionCallback connectionCallback = new ConnectionCallback() {
@Override
public void onServiceConnect() {
// Do something when service connects successfully
}

@Override
public void onServiceDisconnect() {
// Do something when service connects unsuccessfully
}
};

调用VisionManager.init()方法,将此工程的context和connectionCallback 作为入参,建立与能力引擎的连接,context应为ohos.aafwk.ability.Ability或ohos.aafwk.ability.AbilitySlice的实例或子类实例。

int result = VisionManager.init(context, connectionCallback);

在收到onServiceConnect回调连接服务成功后,实例化IBarcodeDetector接口,将此工程的context作为入参。

IBarcodeDetector barcodeDetector = VisionManager.getBarcodeDetector(context);

定义码生成图像的尺寸,并根据图像大小分配字节流数组空间。

final int SAMPLE_LENGTH = 152;
byte[] byteArray = new byte[SAMPLE_LENGTH * SAMPLE_LENGTH * 4];

调用IBarcodeDetector的detect()方法,根据输入的字符串信息生成相应的二维码图片字节流。

int result = barcodeDetector.detect(“This is a TestCase of IBarcodeDetector”, byteArray, SAMPLE_LENGTH, SAMPLE_LENGTH);

如果返回值为0,表明调用成功。后续可以利用API将解码流转换为图片源,简要示例如下:

InputStream inputStream = new ByteArrayInputStream(byteArray);
ImageSource imageSource = ImageSource.create(inputStream, null);

当码生成能力使用完毕后,调用IBarcodeDetector的release()方法,释放资源。

result = barcodeDetector.release();

调用VisionManager.destroy()方法,断开与能力引擎的连接。

VisionManager.destroy();

🚀 如未找到文章请搜索栏搜素 | Ctrl+D收藏本站 | 联系邮箱:15810050733@qq.com