代码之家  ›  专栏  ›  技术社区  ›  Euclécio

使用zxing lib从二维码中获取原始字节(或从位矩阵转换)

  •  1
  • Euclécio  · 技术社区  · 8 年前

    我需要 byte[] array 从编码到 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;
    

    生成二维码的功能:

    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() 请求的是 位矩阵 .

    有人可以告诉我出了什么问题,或者告诉我其他获取二维码的方法 byte 大堆

    1 回复  |  直到 8 年前
        1
  •  1
  •   Euclécio    3 年前

    我找到了使用库解码位图的解决方案: 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;
    }
    

    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");
    }