gpt4 book ai didi

java - 使用 zxing lib 从 QR 码获取原始字节(或从 BitMatrix 转换)

转载 作者:太空宇宙 更新时间:2023-11-04 11:06:26 25 4
gpt4 key购买 nike

我需要从编码为BitMatrix的QR码中获取byte[] array。这是我的代码:

// imports
import com.google.zxing.BarcodeFormat;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.DecoderResult;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.datamatrix.decoder.Decoder;

生成二维码的函数:

public byte[] createQRCode() {
String qrCodeData = "Hello world";
String charset = "UTF-8";
BitMatrix matrix = null;
Writer writer = new QRCodeWriter();

try {
matrix = writer.encode(new String(qrCodeData.getBytes(charset), charset), BarcodeFormat.QR_CODE, qrCodeheight, qrCodewidth);
} catch (UnsupportedEncodingException e) {
return;
}
catch (WriterException e) {
return;
}

DecoderResult decoderResult = null;
try {
decoderResult = new Decoder().decode(matrix);
} catch (ChecksumException e) {
return;
} catch (FormatException e) {
// Always this exception is throwed
}

byte[] cmd = decoderResult.getRawBytes();`
return cmd;
}

执行总是在 FormatException 上停止,即使 Decode().decode() 请求的参数是 BitMatrix

有人可以告诉我出了什么问题,或者告诉我其他获取 QR 码 byte 数组的方法吗?

最佳答案

我找到了使用库来解码位图的解决方案: https://github.com/imrankst1221/Thermal-Printer-in-Android

将字符串编码为二维码位图的函数:

public Bitmap encodeToQrCode(String text, int width, int height){
QRCodeWriter writer = new QRCodeWriter();
BitMatrix matrix = null;
try {
matrix = writer.encode(text, BarcodeFormat.QR_CODE, width, height);
} catch (WriterException ex) {
//
}
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++){
for (int y = 0; y < height; y++){
bmp.setPixel(x, y, matrix.get(x,y) ? Color.BLACK : Color.WHITE);
}
}
return bmp;
}

然后我使用找到的库中的 Utils 将位图解码为字节:

try {
Bitmap bmp = encodeToQrCode("Hello world", 200, 200);
if (bmp != null ) {
byte[] command = Utils.decodeBitmap(bmp);
BluetoothPrintDriver.BT_Write(command);
} else {
Log.e("Print Photo error", "file not found");
}
} catch (Exception e) {
e.printStackTrace();
Log.e("PrintTools", "file not found");
}

关于java - 使用 zxing lib 从 QR 码获取原始字节(或从 BitMatrix 转换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46435118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com