Learning Summary of "Java Generating Two-Dimensional Code" on Muchow.com

Time: Friday, 23 June 2017
Note: Part of the content of this article is from Mucho.com. @ Mu Course Net: http://www.imooc.com
Teaching sample source code: none
Personal learning source code: https://github.com/zccodere/s...

Chapter 1: The concept of two-dimensional codes

Overview of 1-1 Two-Dimensional Code

Two-Dimensional Code Diagram

Use scenarios

Catalog

The Concept of Two-Dimensional Code
 Development History of Two-Dimensional Codes
 Two-Dimensional Code Classification
 Advantages and disadvantages of two-dimensional codes
QR Code
 Explanation of examples

The Concept of Two-Dimensional Code

Two-dimensional bar code (2-dimensional bar code) is a kind of graph which records data symbolic information by black-and-white graphics which distribute in the plane (two-dimensional direction) according to certain rules in a given geometric figure.

Chapter 2: Development History of Two-Dimensional Code

Development History of 2-1 Two-Dimensional Code

History of Development

One-dimensional barcode

One-dimensional barcode is a set of markers which are different in thickness, black-and-white (or color) bars, blanks and their corresponding characters (digital letters), that is, traditional barcode.

One-dimensional bar code schematic diagram

QR code

Two-dimensional bar code records data symbolic information by using bar and space-to-space graphics which are distributed on the plane (two-dimensional direction) according to certain rules of a certain geometric figure.

Two-dimensional bar code schematic diagram

Chapter 3: Classification of two-dimensional codes

Classification of 3-1 2-D codes

There are also many different codes for two-dimensional barcodes. As far as the coding principle of codes is concerned, they are usually divided into three types:

1. Linear stacked two-dimensional codes
 2. Matrix Two-Dimensional Codes
 3. Postal code

Linear stacked two-dimensional codes

Coding Principle: Based on one-dimensional bar code, it can be stacked into two or more lines as needed.

Linear Stacked Two-Dimensional Code Diagram

Matrix Two-Dimensional Code

In a rectangular space, the black and white pixels are encoded by different distributions in the matrix.
In the position of the corresponding elements of the matrix, the occurrence of points (square points, circles or other shapes) is used to represent the binary "1", and the absence of points is used to represent the binary "0".

Matrix Two-Dimensional Code Diagram

Postal code

Postal codes are encoded by bars of different lengths and are mainly used for mail coding, such as POSTNET, BPO 4-STATE.

Chapter 4: Advantages and disadvantages of two-dimensional codes

Advantages and disadvantages of 4-1 two-dimensional code

Advantage

High density coding, large information capacity
    (Up to 1850 capital letters or 2710 digits or 1108 bytes or 500 Chinese characters)
Wide coding range
    It can encode pictures, words, fingerprints and digitized information, and display them with barcode.
Strong fault tolerance
 High Decoding Reliability
 Encryption measures can be introduced
 Low Cost, Easy to Make and Durable

shortcoming

Two-dimensional code technology has become a new channel for mobile virus and phishing websites to spread
 Information Leakage

Chapter 5: QR Code

5-1 QR Code

Three popular international standards are as follows:

PDF417: Chinese is not supported
 DM: Patents are not disclosed. Patent fees should be paid.
QR Code: Patent disclosure, support for Chinese

QR Code has advantages over other two-dimensional codes

Speed of reading
 High data density
 Small occupancy space

QR Code is a matrix two-dimensional code symbol developed by Denso Company of Japan in 1994. Its full name is Quick Response Code.

Sketch Map

The Method of Generating Two-Dimensional Code by JSP

Using third-party jar s, such as zxing and qrcodejar
 Javascript, such as jquery.qrcode.js

Chapter 6: Explanation of Examples

6-1 Preparations for Example Explanation

zxing address

https://github.com/zxing/zxing

Maven coordinates

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

6-2 uses zxing to generate two-dimensional codes

Code demonstration:

package com.myimooc.zxing;

import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * Generating two-dimensional codes
 * @author ZhangCheng on 2017-06-23
 */
public class CreateQRCode {

    public static void main(String[] args) {
        // Define the width and height of the image
        int width = 300;
        int height = 300;
        // Define the format of the picture
        String format = "png";
        // Defining the content of two-dimensional codes
        String contents = "www.imooc.com";
        
        Path file = new File("D:/img.png").toPath();
        // Defining parameters of two-dimensional codes
        HashMap<EncodeHintType,Object> hints = new HashMap<EncodeHintType,Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// Setting character encoding
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);// Setting Fault Tolerance Level
        hints.put(EncodeHintType.MARGIN, 2);// Set margin (default 5)
        
        // Generating two-dimensional codes
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height,hints);
            MatrixToImageWriter.writeToPath(bitMatrix, format, file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

6-3 Two-Dimensional Code Resolution Using zxing

Code demonstration:

package com.myimooc.zxing;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javax.imageio.ImageIO;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

/**
 * Reading Two-Dimensional Code
 * @author ZhangCheng on 2017-06-23
 */
public class ReadQRCode {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args) {
        
        MultiFormatReader formatReader = new MultiFormatReader();
        
        // Define two-dimensional code file path
        File file = new File("D:/img.png");
        // Read the picture file and identify it as a picture stream
        BufferedImage image;
        try {
            image = ImageIO.read(file);

            BinaryBitmap binaryBitmap = 
                    new BinaryBitmap(
                    new HybridBinarizer(
                    new BufferedImageLuminanceSource(image)));
            // Defining parameters of two-dimensional codes
            HashMap hints = new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// Setting character encoding
            // Analytic Two-Dimensional Code
            Result result = formatReader.decode(binaryBitmap,hints);
            
            System.out.println("Analytical results:"+result.toString());
            System.out.println("Format type:"+result.getBarcodeFormat());
            System.out.println("Text content:"+result.getText());
            
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
    }

}

6-4 Generates and parses two-dimensional codes using QR Code

QRCode

Generation: http://www.swetake.com/qrcode/index-e.html
 Read: https://osdn.jp/projects/qrcode/

Code demonstration

1. Generating two-dimensional codes

package com.myimooc.qrcode;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

import com.swetake.util.Qrcode;

/**
 * Generate two-dimensional code through Qrcode
 * 
 * @author ZhangCheng on 2017-06-23
 */
public class CreateQRCode {

    public static void main(String[] args) throws Exception {

        Qrcode x = new Qrcode();

        // Content of two-dimensional code display
        String qrData = "www.imooc.com";
        int version = 7;
        int width = 67 + 12 * (version - 1);
        int height = 67 + 12 * (version - 1);
        // Setting two-dimensional code error removal rate, we can choose L(7%), M(15%), Q(25%) and H(30%). The higher the error removal rate, the less information can be stored, but the clearer the two-dimensional code is.
        x.setQrcodeErrorCorrect('M');// Error Correction Level
        x.setQrcodeEncodeMode('B');// N stands for numbers, A for z-Z, B for other characters
        // Set the version number, the range of value is 1-40. The larger the size of the value, the larger the information that can be stored.
        x.setQrcodeVersion(version);

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        Graphics2D gs = bufferedImage.createGraphics();
        // set a property
        gs.setBackground(Color.WHITE);
        gs.setColor(Color.BLACK);
        gs.clearRect(0, 0, width, height);

        // Offset
        int pixoff = 2;

        byte[] d = qrData.getBytes("gb2312");
        if (d.length > 0 && d.length < 120) {
            boolean[][] s = x.calQrcode(d);

            for (int i = 0; i < s.length; i++) {
                for (int j = 0; j < s.length; j++) {
                    if (s[j][i]) {
                        gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                    }
                }
            }
        }
        
        gs.dispose();
        bufferedImage.flush();
        
        ImageIO.write(bufferedImage, "png", new File("D:/qrcode.png"));
    }

}

2. When reading two-dimensional code, QRCodeImage interface should be implemented.

package com.myimooc.qrcode;

import java.awt.image.BufferedImage;

import jp.sourceforge.qrcode.data.QRCodeImage;

/**
 * When reading two-dimensional code, QRCodeImage interface should be implemented.
 * 
 * @author ZhangCheng on 2017-06-23
 */
public class MyQRCodeImage implements QRCodeImage{
    
    BufferedImage bufferedImage;
    
    public MyQRCodeImage(BufferedImage bufferedImage){
        this.bufferedImage = bufferedImage;
    }
    
    @Override
    public int getHeight() {
        return bufferedImage.getHeight();
    }

    @Override
    public int getPixel(int arg0, int arg1) {
        return bufferedImage.getRGB(arg0, arg1);
    }

    @Override
    public int getWidth() {
        return bufferedImage.getWidth();
    }
    
    
    
}

3. Read two-dimensional code

package com.myimooc.qrcode;

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

import jp.sourceforge.qrcode.QRCodeDecoder;

/**
 * Read two-dimensional code through Qrcode
 * 
 * @author ZhangCheng on 2017-06-23
 */
public class ReadQRCode {

    public static void main(String[] args) throws Exception {
        
        File file = new File("D:/qrcode.png");
        
        BufferedImage bufferedImage = ImageIO.read(file);
        
        QRCodeDecoder codeDecoder = new QRCodeDecoder();
        
        String result = new String(codeDecoder.decode(new MyQRCodeImage(bufferedImage)),"gb2312");
        
        System.out.println(result);
    }

}

6-5 jquery-qrcode to generate two-dimensional codes

jquery-qrcode

Address: https://github.com/jeromeetienne/jquery-qrcode

Code demonstration:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Generating two-dimensional codes</title>

<script type="text/javascript" src="static/js/jquery.min.js"></script>
<script type="text/javascript" src="static/js/jquery.qrcode.min.js"></script>

</head>
<body>

The generated two-dimensional codes are as follows:<br>

<div id="qrcode"></div>

<script type="text/javascript">
            
    $('#qrcode').qrcode("www.imooc.com");
        
</script>

</body>
</html>

The results are as follows:

6-6 Other Forms of Two-Dimensional Codes

Two-dimensional codes can do the same.

6-7 Two-Dimensional Code Extension

Why does our two-dimensional code scan out text instead of links?

How to implement two-dimensional code scanning to install mobile phone software? Take Mucho Network as an Example

How to realize two-dimensional code scanning business card?

VCard is the basic format of standard communication book

VCard specification

code implementation

Chapter 7: Summary of Courses

7-1 Summary

Keywords: Java QRCode Google JQuery

Added by Avendium on Thu, 20 Jun 2019 02:49:59 +0300