Search code examples
javazxing

com.google.zxing.NotFoundException while using zxing to decode qrcode


We are using zxing to decode qrcode from images, most of qrcode could normally be extracted from the original images, but some not. I will show the decoder codes and shall we together discuss about what causes NotFoundException and find out solutions.

First of all, need some zxing dependencies:

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.2.1</version>
</dependency>

<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>javase</artifactId>
  <version>3.2.1</version>
</dependency>

Then see the detail codes:

 public static String decodeQrCode(BufferedImage image) throws DependencyServiceException
{
    // Convert the image to a binary bitmap source
    LuminanceSource source = new BufferedImageLuminanceSource(image);
    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

    // Decode the barcode
    QRCodeReader reader = new QRCodeReader();
    Result result = null;
    try
    {
        result = reader.decode(bitmap);
    }
    catch (NotFoundException | ChecksumException | FormatException e)
    {
        throw new DependencyServiceException(e);
    }
    return result == null ? null : result.getText();
}

public static void main(String[] args)
{
    File file = new File("/tmp/ivan_qr_code.jpg");
    String qrCodeOriginUrlExtracted = "";
    try
    {
        FileInputStream imageInFile = new FileInputStream(file);
        byte imageData[] = new byte[(int) file.length()];
        imageInFile.read(imageData);

        String qrCodeBase64 = Base64.encodeBase64URLSafeString(imageData);
        BufferedImage image = Base64StringToImageUtil.generateImageFromString(qrCodeBase64);
        qrCodeOriginUrlExtracted = QrCodeDecoderUtil.decodeQrCode(image);
        imageInFile.close();
    }
    catch (Exception e)
    {
        // TODO: handle exception
    }
    System.out.println(String.format("Extracted text from qr code: %1$s", qrCodeOriginUrlExtracted));
}

Errors generated:

Exception in thread "main"  {"errorCode": "3000", "debugInfo":"null","message": "com.google.zxing.NotFoundException"}
at com.waijule.common.util.image.QrCodeDecoderUtil.decodeQrCode(QrCodeDecoderUtil.java:44)
at com.waijule.common.util.image.QrCodeDecoderUtil.main(QrCodeDecoderUtil.java:58)

Caused by: com.google.zxing.NotFoundException

The template qr code provided as following:

enter image description here

Thanks for all the little helps.


Solution

  • On the whole, the decode method depends on the specific circumstance, DecodeHintType and barcode reader need to specify in advance. Refer to the open source of https://zxing.org/w/decode.jspx from zxing, pay attention to the method 'processImage'.

    Thanks for the followers these days.