HarmonyOS AI基础技术赋能之生成二维码 原创 精华
引言
在实际应用开发中,时不时的会遇到AI领域相关的一些技术,本节主要详细讲述一下生成二维码技术,二维码可能涉及在各领域中,如:社交或通讯类应用、购物或支付类应用等。所以对于HarmonyOS开发者而言,也需要了解和掌握HarmonyOS AI领域相关技术,这对于每一个HarmonyOS开发者,也是一项必不可少的专业技能。
功能介绍
生成二维码主要根据开发者给定的字符串信息和二维码图片尺寸,返回相应的二维码图片字节流。调用方可以通过二维码字节流生成二维码图片。
指南
1、创建二维码
1.1 实例化接口,获取二维码侦测器
IBarcodeDetector barcodeDetector
=VisionManager.getBarcodeDetector(QRCodeAbilitySlice.this);
1.2 定义码生成图像的尺寸
final int SAMPLE_LENGTH = 500;
1.3 根据图像的大小,分配字节流数组的空间
byte[] byteArray = new byte[SAMPLE_LENGTH * SAMPLE_LENGTH * 4];
1.4 调用IBarcodeDetector的detect()方法,根据输入的字符串信息barText生成相应的二维码图片字节流
barcodeDetector.detect(barText,byteArray,SAMPLE_LENGTH,SAMPLE_LENGTH);
1.5 释放侦测器
barcodeDetector.release();
1.6 通过SourceOptions指定数据源的格式信息
ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
1.7 定义图片格式
srcOpts.formatHint = "image/png";
1.8 创建图片源
ImageSource imgSource= ImageSource.create(byteArray,srcOpts);
1.9 创建图像解码选项
ImageSource.DecodingOptions decodingOpts =new
ImageSource.DecodingOptions ();
decodingOpts.desiredPixelFormat= PixelFormat.ARGB_8888;
1.10 通过图片源创建PixelMap
PixelMap pMap =imgSource.createPixelmap(decodingOpts);
1.11 赋值到图片标签
imgQrCode.setPixelMap(pMap);
1.12 释放资源
barcodeDetector.release ();
imgSource.release ();
if (pMap! =null)
{
pMap.release ();
}
1.13 断开与能力引擎的连接
VisionManager.destroy ();
2. 定义ConnectionCallback回调,实现连接能力引擎成功与否后的操作
ConnectionCallback connectionCallback = new ConnectionCallback () {
@Override
public void onServiceConnect () {
2.1需要生成二维码的字符串
String barText= "";
2.2连接成功生成二维码
createQRCode(barText);
}
@Override
public void onServiceDisconnect () {
// Do something when service connects unsuccessfully
}
};
3.调用VisionManager.init()方法,将此工程的context和connectionCallback 作为入参,建立与能力引擎的连接
int result = VisionManager.init(context, connectionCallback);
示例代码
1、xml布局
2、案例代码
实现效果
更多原创内容请关注:软通动力HarmonyOS学院
HarmonyOS开发中,基础知识尤为重要
希望大佬持续分享基础知识
软通动力加油加油