HarmonyOS zxing二维码

在使用@ohos/zxing构建二维码,想根据一些文字生成二维码并且显示在Image组件上,如何实现?

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu

请参考示例如下:首先安装三方库。

ohpm install @ohos/zxing 

QrCodePage.ets

import { BarcodeFormat } from '@ohos/zxing';
import QRCode from './QRCode'
import image from '@ohos.multimedia.image'

@Entry
@ComponentV2
struct QrCodePage {
  @Local pixelMap: image.PixelMap | undefined = undefined
  @Local message: string = ''
  @Local inputText: string = ''
  qrcode = new QRCode()

  async encode() {
    this.pixelMap = await this.qrcode.encode(this.inputText, {
      width: 260,
      height: 260,
      format: BarcodeFormat.QR_CODE
    })
  }

  async decode() {
    try {
      this.message = await this.qrcode.decode(this.pixelMap as image.PixelMap, {
        width: 260,
        height: 260,
        format: BarcodeFormat.QR_CODE
      })
    } catch (err) {
      console.log('[Demo] decode error:' + JSON.stringify(err));
    }
  }

  build() {
    Column() {
      if (this.pixelMap) {
        Image(this.pixelMap).width(260).height(260).margin(30)
      }
      Text('解析结果:' + this.message).fontSize(14)
      TextInput({ placeholder: 'input your word', text: this.inputText })
        .height(60)
        .border({ width: 5, color: Color.Red })
        .placeholderColor(Color.Blue)
        .placeholderFont({
          size: 20,
          weight: FontWeight.Normal,
          family: "sans-serif",
          style: FontStyle.Italic
        })
        .caretColor(Color.Blue)
        .enterKeyType(EnterKeyType.Search)
        .onChange((value: string) => {
          this.inputText = value
        })
      Button('生成二维码').fontSize(25).width(300).margin(20).onClick(() => this.encode())
      Button('解析二维码').fontSize(25).width(300).margin(20).onClick(() => this.decode())
    }

  }
}

QRCode.ets

import {
  BarcodeFormat,
  MultiFormatWriter,
  BitMatrix,
  ZXingStringEncoding,
  EncodeHintType,
  MultiFormatReader,
  DecodeHintType,
  RGBLuminanceSource,
  BinaryBitmap,
  HybridBinarizer
} from '@ohos/zxing';
import image from '@ohos.multimedia.image';
import { getMatrixPixelData } from './imageUtils'

export default class QRCode {
  constructor() {
  }

  private typedArrayToBuffer(array: Uint32Array): ArrayBuffer {
    return array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset)
  }

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

  async decode(image: image.PixelMap, params: Params): Promise<string> {
    const width = params.width
    const height = params.height
    const format = params.format ? params.format : BarcodeFormat.QR_CODE
    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: Map<DecodeHintType, Array<BarcodeFormat>> = new Map();

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

interface Params {
  width: number,
  height: number,
  format?: BarcodeFormat
}

imageUtils.ets

import image from '@ohos.multimedia.image';
import ability_featureability from '@ohos.ability.featureAbility'
import { BitMatrix } from '@ohos/zxing';

interface loadLocalImageBufferResult {
  pixelMap: PixelMap
  int32Array: Int32Array
}

export function createEmptyPixelMap(): Promise<PixelMap> {
  let initializationOpts: image.InitializationOptions = {
    "alphaType": 1,
    "editable": true,
    "pixelFormat": 3,
    "scaleMode": 1,
    "size": { "width": 1, "height": 1 },
  };
  return image.createPixelMap(new ArrayBuffer(1), initializationOpts)
}

export function getPixelMap(buffer: ArrayBuffer, width: number, height: number): Promise<PixelMap> {
  return new Promise<PixelMap>((resolve, reject) => {
    // 配置创建PixelMap的参数
    let initializationOpts: image.InitializationOptions = {
      "alphaType": 1,
      "editable": true,
      "pixelFormat": 3,
      "scaleMode": 1,
      "size": { "width": width, "height": height },
    };

    // 根据二维码图片数据创建PixelMap
    image.createPixelMap(buffer, initializationOpts, (err, data) => {
      if (err) {
        console.error(TAG + 'getPixelMap error code is  ' + err.code);
        console.error(TAG + 'getPixelMap error msg is ' + err.message);
      } else {
        // 读取新创建的PixelMap
        let pixelBytesNumber = data.getPixelBytesNumber()
        console.error(TAG + 'getPixelMap pixelBytesNumber ' + pixelBytesNumber);
        console.error(TAG + 'getPixelMap Succeed');
        resolve(data)
      }
    });
  })
}

export function getPixelMapInt32ArrayData(pixelMap: PixelMap): Promise<Int32Array> {
  return new Promise<Int32Array>((resolve, reject) => {
    // 读取新创建的PixelMap
    let pixelBytesNumber: number = pixelMap.getPixelBytesNumber()
    console.error(TAG + 'getPixelMapInt32ArrayData pixelBytesNumber: ' + pixelBytesNumber);
    let readPixelsToBuffer = new ArrayBuffer(pixelBytesNumber);
    let readPixelsToUnit8Arr: Int32Array = new Int32Array(readPixelsToBuffer);
    pixelMap.readPixelsToBuffer(readPixelsToBuffer, (InfoErr, InfoData) => {
      if (InfoErr) {
        console.error(TAG + 'getPixelMapInt32ArrayData error code is  ' + InfoErr.code);
        console.error(TAG + 'getPixelMapInt32ArrayData error msg is ' + InfoErr.message);
      } else {
        console.log(TAG + 'getPixelMapInt32ArrayData success');
        console.log(TAG + 'getPixelMapInt32ArrayData readPixelsToUnit8Arr size:' + readPixelsToUnit8Arr.length);
        console.log(TAG + 'getPixelMapInt32ArrayData readPixelsToUnit8Arr:' + JSON.stringify(readPixelsToUnit8Arr));
        resolve(readPixelsToUnit8Arr);
      }
    });
  })
}
export function getMatrixPixelData(matrix: BitMatrix, width: number, height: number) {
  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;
}

let TAG = "imageUtils-----------------------";
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 支持扫描二维吗?
397浏览 • 1回复 待解决
HarmonyOS 二维生成的demo
243浏览 • 2回复 待解决
HarmonyOS 二维条码扫描识别
611浏览 • 1回复 待解决
HarmonyOS如何无感知扫描二维
360浏览 • 1回复 待解决
HarmonyOS扫描二维的方案是什么?
2074浏览 • 1回复 待解决
HarmonyOS 二维显示和导出base64
54浏览 • 1回复 待解决
二维扫描三方库推荐
201浏览 • 1回复 待解决
HarmonyOS h5加载二维屏幕变亮
36浏览 • 1回复 待解决
Canvas组件实现二维中心内嵌图标
951浏览 • 1回复 待解决
openHarmony-Api8项目,如何生成二维
974浏览 • 0回复 待解决