【HarmonyOS】Stage模型二维码/条码生成与解析

HarmonyOS的官方API中提供了QRCode组件(QRCode-基础组件-组件参考(基于ArkTS的声明式开发范式)-ArkTS API参考-HarmonyOS应用开发),这个组件有个缺点只能用于显示二维码,无法显示条码与解析码内容,下面给大家介绍一个功能强大的三方库@ohos/zxing,效果如下。

【开发步骤】

Gitee仓库中的示例代码很全,如果只是需要简单接入的话,可以精简一下代码。

一、引入三方库

首先,我们需要导入这个ohpm的组件库,可以参考demo中的命令行方式导入:

"ohpm install @ohos/zxing"

另一种方式是在oh-package.json5中配置,这边的版本选择的是2.0.0版本,配置如下:

javascript 复制代码
 "dependencies": {
   "@ohos/zxing": "2.0.0"
 }

二、完成解析与生成相关代码

在src/main/ets目录下创建码解析与生成的工具类文件QRCode.ets

javascript 复制代码
import {
 BarcodeFormat,
 MultiFormatWriter,
 BitMatrix,
 EncodeHintType,
 MultiFormatReader,
 DecodeHintType,
 RGBLuminanceSource,
 BinaryBitmap,
 HybridBinarizer
} from '@ohos/zxing';
import image from '@ohos.multimedia.image';

export default class QRCode {
 constructor() {

 }

 async encode(content: string, params: {
   width: number,
   height: number,
   format?: BarcodeFormat
 }): Promise<image.PixelMap> {
   const {width,height,format=BarcodeFormat.QR_CODE} = params
   const encodeHintTypeMap = new Map();
   // 设置二维码空白的宽度
   encodeHintTypeMap.set(EncodeHintType.MARGIN, 0);
   const writer: MultiFormatWriter = new MultiFormatWriter();
   let matrix: BitMatrix = writer.encode(content, format, width, height, encodeHintTypeMap);
   const PixelData = this.getMatrixPixelData(matrix, matrix.getWidth(), matrix.getHeight())
   return await image.createPixelMap(PixelData.buffer, {
     size: {
       width, height
     }
   })
 }

 async decode(image: image.PixelMap, params: {
   width: number,
   height: number,
   format?: BarcodeFormat
 }): Promise<string> {
   const {width,height,format=BarcodeFormat.QR_CODE} = params
   let num=image.getPixelBytesNumber()
   let arrayBuffer:ArrayBuffer=new ArrayBuffer(num);
   await image.readPixelsToBuffer(arrayBuffer)
   const int32Array=new Int32Array(arrayBuffer)
   const luminanceSource=new RGBLuminanceSource(int32Array,width,height)
   const binaryBitmap=new BinaryBitmap(new HybridBinarizer(luminanceSource))
   const reader=new MultiFormatReader()
   const hints=new Map();

   hints.set(DecodeHintType.POSSIBLE_FORMATS,[format]);
   reader.setHints(hints);
   let result=reader.decode(binaryBitmap);
   let text=result.getText();
   return text;
 }

 getMatrixPixelData(matrix, width, height) {
   const BLACK = 0xFF000000;
   const WHITE = 0xFFFFFFFF;
   const pixels = new Uint32Array(width * height);
   for (let y = 0; y < height; y++) {
     let offset = y * width;
     for (let x = 0; x < width; x++) {
       pixels[offset + x] = matrix.get(x, y) ? BLACK : WHITE;
     }
   }
   return pixels;
 }

}

encode编码方法:根据输入的参数生成码的方法,可以通过传入不同的BarcodeFormat完成不同格式的码的生成。

decode解码方法:对image组件中图片的pixelMap,进行解码操作获取对应的码值

getMatrixPixelData:这个方法是将matrix转成PixelData,用于获取pixelMap的buffer,我们可以在这个方法中定义条码的颜色

三、使用工具类完成解析与生成

最后我们在page页中使用刚刚的方法就可以完成码的解析与生成功能。这边需要注意的是encode()和decode()方法都是耗时操作,我们使用async/await来进行异步处理操作

javascript 复制代码
import { BarcodeFormat } from '@ohos/zxing';
import QRCode from '../util/QRCode'

@Entry

@Component
struct Index {
 @State message: string = 'Hello World'
 @State pixelMap: PixelMap = undefined
 qrcode = new QRCode()

 async encode() {
   this.pixelMap = await this.qrcode.encode("this is barcode", {
     width: 260,
     height: 80,
     format: BarcodeFormat.CODE_128
   })
 }
 async decode() {
   try {
     this.message = await this.qrcode.decode(this.pixelMap, {
       width: 260,
       height: 80,
       format: BarcodeFormat.CODE_128
     })
   } catch (err) {

     console.log('[Demo] decode error:' + JSON.stringify(err));
   }
 }

 build() {
   Row() {
     Column() {
       Text(this.message)
         .fontSize(50)
         .fontWeight(FontWeight.Bold)
       Image(this.pixelMap).width(260).height(80).margin(30)
       Button('生成一维码').fontSize(25).width(300).margin(20).onClick(() => {
         this.encode();
       })
       Button('解析一维码').fontSize(25).width(300).margin(20).onClick(() => {
         this.decode();
       })

     }
     .width('100%')
   }
   .height('100%')
 }


}

上面代码中使用的码的格式是条码格式:BarcodeFormat.CODE_128,如果需要使用二维码也可以将这边的格式修改为:BarcodeFormat.QR_CODE

【最后】

至此我们就完成了Stage模型中条码生成与解析的基本操作,如果需要进一步自定义可以参考demo工程:OpenHarmony-TPC/zxing (gitee.com)。

相关推荐
OH_TPC5 小时前
ImageKnifePro 源码解读(四):降采样策略族——按显示尺寸改衣服,不按原尺寸硬塞
harmonyos
民办二本的神5 小时前
AI 助手升级后聊天记录又丢了(二):数据一直都在,丢的是"看见"
harmonyos
huang_xiaoen1 天前
鸿蒙手机远程控制电脑哪个好用?2026鸿蒙远控软件横测推荐
华为·harmonyos·远程工作·远程工具·远程办公
爱写Bug的浮游2 天前
初识仓颉:5 分钟看懂核心语法
harmonyos·编程语言
程序猿追3 天前
鸿蒙 PC 的 Ionic 工单有两个错误,按下生成后光标该去哪儿
华为·harmonyos
KevinChaos3 天前
随手备忘录手记 04|HarmonyOS 7.0新特性实验:物品图鉴的加载逻辑
华为·harmonyos
Sirius_Ji3 天前
从硬解基座到字幕与滤镜链:ffmpeg-for-HarmonyOS v0.3.2
harmonyos
用户86194177207413 天前
uni-app 鸿蒙端提现点不动?我用 UTS 插件补上了微信"确认收款"
微信·harmonyos
码间留白3 天前
uni-app 鸿蒙端提现点不动?我用 UTS 插件补上了微信"确认收款"
uni-app·harmonyos·鸿蒙·uts插件·微信商家转账
GitCode官方4 天前
开源鸿蒙跨平台直播|AI 时代,用 cj-tauri 开发鸿蒙 PC 应用
人工智能·华为·harmonyos·atomgit