用java生成一个简单的二维码

  1. 首先创建一个maven项目
  2. pom.xml引入zxing依赖
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.0</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.0.0</version>
</dependency>

3.创建CreateQRCode类

package com.example.demo30;

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;

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

//生成二维码
public class CreateQRCode {
    public static void main(String[] args) {

        int width = 300;        //定义图片宽度
        int height = 300;       //定义图片高度
        String format = "png";      //定义图片格式
        String content = "https://blog..net/weixin_45537947";     //定义二维码内容

        //定义二维码的参数
        HashMap hashMap = new HashMap();
        hashMap.put(EncodeHintType.CHARACTER_SET, "utf-8");     //设置编码
        hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);       //设置容错等级,等级越高,容量越小
        hashMap.put(EncodeHintType.MARGIN, 2);          //设置边距
        //生成二维码
        try {
            //生成矩阵
            //                                                   内容              格式          宽       高
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hashMap);
            Path file = new File("D:/img.png").toPath();        //设置路径
            MatrixToImageWriter.writeToPath(bitMatrix, format, file);       //输出图像
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4、启动运行就可以生成二维码了 我的生成地址是在“D:/img.png”。

经验分享 程序员 微信小程序 职场和发展