QR Code encoding and decoding using zxing

前端 未结 6 2090
孤城傲影
孤城傲影 2020-11-27 10:05

Okay, so I\'m going to take the off chance that someone here has used zxing before. I\'m developing a Java application, and one of the things it needs to do is encode a byte

6条回答
  •  隐瞒了意图╮
    2020-11-27 10:57

    I tried using ISO-8859-1 as said in the first answer. All went ok on encoding, but when I tried to get the byte[] using result string on decoding, all negative bytes became the character 63 (question mark). The following code does not work:

    // Encoding works great
    byte[] contents = new byte[]{-1};
    QRCodeWriter codeWriter = new QRCodeWriter();
    BitMatrix bitMatrix = codeWriter.encode(new String(contents, Charset.forName("ISO-8859-1")), BarcodeFormat.QR_CODE, w, h);
    
    // Decodes like this fails
    LuminanceSource ls = new BufferedImageLuminanceSource(encodedBufferedImage);
    Result result = new QRCodeReader().decode(new BinaryBitmap( new HybridBinarizer(ls)));
    byte[] resultBytes = result.getText().getBytes(Charset.forName("ISO-8859-1")); // a byte[] with byte 63 is given
    return resultBytes;
    

    It looks so strange because the API in a very old version (don't know exactly) had a method thar works well:

    Vector byteSegments = result.getByteSegments();
    

    So I tried to search why this method was removed and realized that there is a way to get ByteSegments, through metadata. So my decode method looks like:

    // Decodes like this works perfectly
    LuminanceSource ls = new BufferedImageLuminanceSource(encodedBufferedImage);
    Result result = new QRCodeReader().decode(new BinaryBitmap( new HybridBinarizer(ls)));
    Vector byteSegments = (Vector) result.getResultMetadata().get(ResultMetadataType.BYTE_SEGMENTS);  
    int i = 0;
    int tam = 0;
    for (Object o : byteSegments) {
        byte[] bs = (byte[])o;
        tam += bs.length;
    }
    byte[] resultBytes = new byte[tam];
    i = 0;
    for (Object o : byteSegments) {
        byte[] bs = (byte[])o;
        for (byte b : bs) {
            resultBytes[i++] = b;
        }
    }
    return resultBytes;
    

提交回复
热议问题