2017-09-26 292 views
1

我需要从编码为BitMatrix的QR码中获得byte[] array。这里是我的代码:从QR码获取原始字节与zxing lib(或从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数组?

回答

0

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