-->

Not able to read 2D data matrix in Image

2019-08-13 19:54发布

问题:

I have to read the 2D data matrix bar code from an Image. I am using zxing to read the barcode. This is the code i am using.

import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

public class BarcodeGeneration {

    public static void main(String[] args) throws IOException {
        InputStream barCodeInputStream = new FileInputStream("file.jpg");  
        BufferedImage barCodeBufferedImage = ImageIO.read(barCodeInputStream);  
        LuminanceSource source = new BufferedImageLuminanceSource(barCodeBufferedImage);  
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));  
        Reader reader = new MultiFormatReader();  
        Result result;
        try {
            result = reader.decode(bitmap);
            System.out.println("Barcode text is " + result.getText());
        } catch (NotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ChecksumException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  


    }

}

The problem is i am not getting the output for all the images. I have downloaded an image from net which is working fine. But for the actual input image i am getting the "com.google.zxing.NotFoundException" exception though it has the data. Can anyone help to overcome this problem or give alternate solution to read 2D Data Matrix.!

Thanks

Images: and

回答1:

Its because the 2d matrix is not in the center of the extracted image. So i have resized the image using Image class then it worked.