Get raw bytes from QR Code with zxing lib (or convert from BitMatrix)
I need to get byte[] array
from a QR Code encoded into a BitMatrix
. Here's my code:
// 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;
The function to generate QR Code:
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;
}
Always the execution stop on FormatException
, even the parameter on Decode().decode()
requested is BitMatrix
.
Someone can tell me what's wrong or show me other way to get the QR Code byte
array?
Solution 1:
I found the solution using a library to decode Bitmap: https://github.com/imrankst1221/Thermal-Printer-in-Android
Function to encode String into QR Code Bitmap:
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;
}
Then I decode bitmap to bytes using Utils from the found library:
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");
}