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

时间:2017-09-26 20:19:20

标签: java android qr-code zxing

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

// 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;

生成QR码的功能:

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数组的其他方法吗?

1 个答案:

答案 0 :(得分:0)

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

将字符串编码为QR码位图的功能:

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", "the file isn't exists");
    }
} catch (Exception e) {
    e.printStackTrace();
    Log.e("PrintTools", "the file isn't exists");
}