Java implements terminal/CMD control window to output QR code (in character mode, not picture)

ConsoleQRcode

Output QR code in terminal/console, print QR code characters (not pictures), Java implementation

1. Dependencies

  • Zxing
    • Jar package: https://pan.baidu.com/s/1ZKb8DwsBNIcE_kBQmjHASg?pwd=i4pj
    • Maven
      <dependency>
          <groupId>com.google.zxing</groupId>
          <artifactId>core</artifactId>
          <version>3.5.1</version>
      </dependency>
      

2. Code implementation

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.HashMap;

/**
 * @Author 薄荷你玩
 * @Date 2023/04/16
 * @Website www.bhshare.cn
 */
public class ConsoleQRcode {
    
    
    /**
     * 打印二维码 -> console
     * @param content 二维码内容
     */
    public static void printQRcode(String content) {
    
    
        int width = 1; // 二维码宽度
        int height = 1; // 二维码高度

        // 定义二维码的参数
        HashMap<EncodeHintType, java.io.Serializable> hints = new HashMap<EncodeHintType, java.io.Serializable>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//编码方式
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//纠错等级

        // 打印二维码
        try {
    
    
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            for (int j = 0; j < bitMatrix.getHeight(); j++) {
    
    
                for (int i = 0; i < bitMatrix.getWidth(); i++) {
    
    
                    if (bitMatrix.get(i, j)) {
    
    
                        System.out.print("■");
                    } else {
    
    
                        System.out.print("  ");
                    }

                }
                System.out.println();
            }
        } catch (WriterException e) {
    
    
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
    
    
        String str = "http://www.bhshare.cn";
        printQRcode(str);
    }
}

3. Effect

insert image description here

4. There are defects

  1. It is only valid in the terminal/command line window. The console like IDEA is not easy to use, because the line height of the text output by IDEA is relatively large, resulting in inconsistent width and height of the output content.

    image

  2. When the content of the QR code is complex (the size of the generated QR code will become larger) or the CMD operation window is small, the text will wrap and cause the typesetting to be disordered.

Github:https://github.com/yaokui2018/ConsoleQRcode


Reference article:

https://www.cnblogs.com/qijunhui/p/8284447.html

Guess you like

Origin blog.csdn.net/qq_40738764/article/details/130181727