Java zxing helps when reading bar code (java.lang.NullPointerException at com.google.zxing.client.j2se.BufferedImageLuminanceSource.init)

0

Good afternoon, I'm starting to program with zxing, my question is this: I'm trying to read a barcode, this is my source code:

   private static String readBarcode(String pathname) throws FormatException, ChecksumException, NotFoundException, IOException {

       InputStream qrInputStream = new FileInputStream(pathname);
       BufferedImage qrBufferedImage = ImageIO.read(qrInputStream);

       LuminanceSource source = new BufferedImageLuminanceSource(qrBufferedImage);
       BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
       Reader reader = new MultiFormatReader();
       Result stringBarCode = reader.decode(bitmap);

       return stringBarCode.getText();
   }

The error that it generates is:

  

java.lang.NullPointerException       at com.google.zxing.client.j2se.BufferedImageLuminanceSource. (BufferedImageLuminanceSource.java:39)
      at testWS.TestZXing.readBarcode (TestZXing.java:78)
      at testWS.TestZXing.main (TestZXing.java:50)

I leave an image of the bar code that I am trying to read.

    
asked by Wilsoon 06.03.2017 в 21:47
source

1 answer

2

Good programming practice: Detect early execution errors.

Specifically: the line

  BufferedImage qrBufferedImage = ImageIO.read(qrInputStream);

uses a method that tries to read and decode an image, and that may fail (for example, if the stream does not correspond to a valid image, or decodable) You should be aware of this, and ask yourself: "What will happen here in case of error, throw an exception or return null or what?" It is important to know the answer because that way you can react to the error early. If you do not, and (for example) the method returns a null that you did not contemplate, later you will run into an NPE (null pointer exception), which you have to avoid, because it is not very informative and confusing to debug. / p>

In other words, the line

 LuminanceSource source = new BufferedImageLuminanceSource(qrBufferedImage);

implicitly assumes that qrBufferedImage is not a null. But you have not verified this. Therefore your code is objectionable

Now, we read the doc de ImageIO.read() and says clearly:

  

If not registered ImageReader claims to be able to read the result   stream, null is returned.

And very probably that is the case here. For that reason, it is convenient to add a check:

   BufferedImage qrBufferedImage = ImageIO.read(qrInputStream);
   if(qrBufferedImage ==null) 
        System.err.println("No se pudo leer o decodificar imagen " + pathname);

or, probably better

   BufferedImage qrBufferedImage = ImageIO.read(qrInputStream);
   if(qrBufferedImage ==null) 
        throw new RuntimeException("No se pudo leer o decodificar imagen " + pathname);
    
answered by 08.03.2017 в 19:07