Java generates a simple example of reading barcode and QR code

  • 2021-10-25 06:41:15
  • OfStack

Bar code

A plurality of black stripes and white stripes with different widths are sorted according to a certain coding rule, which is used to express an image identifier of a group of information

Usually represents a string of numbers/letters, and each digit has a special meaning

1 general data capacity 30 digits/letters

2D code

Record data symbol information with a black-and-white figure distributed in a plane (2-dimensional direction) according to a certain geometric figure

It can store more information and represent more data types than 1-dimensional barcode

Can store numbers/letters/Chinese characters/pictures and other information

It can store hundreds to several 10KB characters

Zxing

Zxing is mainly produced by Google, which is used to identify the third square library of 1-D code and 2-D code

Main categories:

BitMatrix bitmap matrix MultiFormatWriter bitmap writer MatrixToImageWriter Write Picture

Maven into Zxing


<dependencies>
        <!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.2.1</version>
        </dependency>

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

Generate a 1-dimensional code java


public static void main(String[] args) {
    generateCode(new File("1dcode.png"), "1390351289", 500, 250);
}
/**
 * @param file     Generated file name 
 * @param code    1 Data information stored by dimension code 
 * @param width    Width of generated picture 
 * @param height   Height of generated picture 
 * @return void
 * */
public static void generateCode(File file, String code, int width, int height){
    //  Defining Bitmap Matrix BitMatrix
    BitMatrix matrix = null;
    try {
        //  Use code_128 Format is encoded and generated 100*25 Barcode of 
        MultiFormatWriter writer = new MultiFormatWriter();

        matrix = writer.encode(code, BarcodeFormat.CODE_128, width, height, null);
    } catch (WriterException e) {
        e.printStackTrace();
    }

    //  Bitmap Matrix BitMatrix Save as Picture 
    try {
        FileOutputStream outputStream = new FileOutputStream(file);
        ImageIO.write(MatrixToImageWriter.toBufferedImage(matrix), "png", outputStream);
        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Note: 1-D code can only store numbers and letters. Other data will be reported as Failed to execute goal org. codehaus. mojo: exec-maven-plugin: 3.0. 0: exec (default-cli) on project MavenDemo: Command execution failed. Error java

Read 1-dimensional code


public static void main(String[] args) {
    readCode(new File("1dcode.png"));
}
/**
 * @param readImage     Read 1 Dimension code picture name 
 * @return void
 * */
public static void readCode(File readImage) {
    try {
        BufferedImage image = ImageIO.read(readImage);
        if (image == null) {
            return;
        }
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

        Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
        hints.put(DecodeHintType.CHARACTER_SET, "gbk");
        hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
        hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);

        Result result = new MultiFormatReader().decode(bitmap, hints);
        System.out.println(result.getText());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Note: When using String class for transcoding, the String class of the third party Apache will be imported when using Java. lang package and Maven guide package

Generate 2-D code


/**  Definition 2 Width of dimension code  */
private final static int WIDTH = 300;
/**  Definition 2 Height of dimension code  */
private final static int HEIGHT = 300;
/**  Definition 2 Format of dimension code  */
private final static String FORMAT = "png";

/**
 * @param file
 * @param content
 * @return void
 * */
public static void generateQRCode(File file, String content) {
    //  Definition 2 Dimension code parameter 
    Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
    //  Set code 
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    //  Set fault tolerance level 
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
    //  Set the margin, which defaults to 5
    hints.put(EncodeHintType.MARGIN, 2);

    try {
        BitMatrix bitMatrix = new MultiFormatWriter()
                .encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
        Path path = file.toPath();
        //  Save to projects and directories 
        MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public static void main(String[] args) {
    generateQRCode(new File("smt.png"), " Shumei Tang Home Furnishing Network ");
}

Read 2-D code


/**
 * @param file     Read 2 File name of dimension code 
 * @return void
 * */
public static void readQRCode(File file) {
    MultiFormatReader reader = new MultiFormatReader();
    try {
        BufferedImage image = ImageIO.read(file);
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
        Map<DecodeHintType, Object> hints = new HashMap<>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        Result result = reader.decode(binaryBitmap, hints);
        System.out.println(" Analytic result : " + new String(result.toString().getBytes("GBK"), "GBK"));
        System.out.println("2 Dimension code format : " + result.getBarcodeFormat());
        System.out.println("2 Dimension code text content : " + new String(result.getText().getBytes("GBK"), "GBK"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public static void main(String[] args) {
    readQRCode(new File("smt.png"));
}

Note: Maven printed console will appear Chinese garbled, in IDEA Setting- > maven- > runner VMoptions:-Dfile. encoding=GB2312; Can be solved

Summarize


Related articles: