如何从 TypeScript 和 Angular 中的原始字节生成 QRCode

How to generate QRCode from raw bytes in TypeScript and Angular

我构建了一个简单的 Web 应用程序,它从端点接收一些代码并生成一个密钥,必须从中生成 QR 码。

结束键是一个Uint8Array,需要做成二维码,我用的是angularx-qrcode库,然后用Uint8Array转成字符串String.fromCharCode.apply(null, uintArray) 然而这种方法被证明对我的情况不起作用。

我需要从数组的原始十六进制值生成 QRCode,但是使用 String.fromCharCode 它似乎生成 UTF-8 字符,从而生成意外字符。

到目前为止,我已经尝试使用库将字符串转换为名为 iconv-lite 的 'ISO-8859-1',但它似乎没有用。

我也试过像这样转换字符串 decodeURIComponent(escape(encodedString));,但是这会抛出一个错误,指出无效的 URI,可能是因为结束键包含无效的字符,这些字符不适用于该函数。

以下是我的字节数组的示例,其长度始终为 20 个字节。 156,0,0,0,0,0,148,131,114,7,121,81,85,9,0,0,84,69,48,171

虽然我认为这个问题也可能与 QR-Code 库本身有关,但在给了它一些之后,我寻找了一个接收 Uint8Array 而不是字符串的 QR-Code 库, 但我没找到。

我的一位同事通过将字符串结尾为 ISO-8859-1 而不是 UTF-8.

设法解决了 android 应用程序上的这个问题

我认为解决方案是直接从字节数组生成 QRCode,这样我就不需要为字符编码而烦恼,但如果有人知道解决此问题的其他方法,我会很乐意尝试。

我需要从这些字节生成的 RAW 字符串,例如第一个字节是 156,十六进制是 9c,所以我需要代表 9c 的字符,但是 9c 它不是 'regular' ASCII 字符,这就是为什么 String.fromCharCode 对我不起作用,结束字符串应该像数组一样长 20 个字节。

据我了解,您在从字节数组生成十六进制字符串时遇到问题? 试试这个功能:

function byteToHex(byte) {
  // convert the possibly signed byte (-128 to 127) to an unsigned byte (0 to 255).
  // if you know, that you only deal with unsigned bytes (Uint8Array), you can omit this line
  const unsignedByte = byte & 0xff;

  // If the number can be represented with only 4 bits (0-15), 
  // the hexadecimal representation of this number is only one char (0-9, a-f). 
  if (unsignedByte < 16) {
    return '0' + unsignedByte.toString(16);
  } else {
    return unsignedByte.toString(16);
  }
}

// bytes is a typed array (Int8Array or Uint8Array)
function toHexString(bytes) {
  // Since the .map() method is not available for typed arrays, 
  // we will convert the typed array to an array using Array.from().
  return Array.from(bytes)
    .map(byte => byteToHex(byte))
    .join('');
}

致谢:

我使用这个库成功解决了我的问题:QR-Code-generator

它允许从字节数组和常规字符串生成二维码。

它非常轻巧,使用起来非常简单,并且支持多种不同的编程语言。 唯一的缺点是它不支持 NPM,而且它的默认 TypeScript 实现有点差,它需要一些调整才能与我的项目一起使用,但最终它完美地工作,它甚至支持 SVG 输出。