1、需要用到的maven依赖
<!-- https://mvnrepository.com/artifact/com.google.zxing/core --><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.3.0</version></dependency>
目前项目大多都是maven项目,我们只需要把上面的依赖放入项目的pom.xml文件中就能自动导入jar包到项目,前提是自己的maven环境都已经搭建好了,相信大家已经搭建好了,这里就不累述了。
2、代码
package com.example.demo.qrcode;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;/**
* <p>Description: </p>
* @author xuyangwei
* @date 2019年9月13日
*/
public class Zxing {public static void main(String[] args) {Zxing zxing = new Zxing();// 传参:二维码内容和生成路径if (zxing.orCode("https://blog.csdn.net/q15102780705/article/details/100060137", "D:\\1.jpg")) {System.out.println("ok,成功");} else {System.out.println("no,失败");}}private boolean orCode(String content, String path) {/** 图片的宽度和高度*/int width = 300;int height = 300;// 图片的格式String format = "png"; // 定义二维码的参数HashMap<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();// 定义字符集编码格式hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 纠错的等级 L > M > Q > H 纠错的能力越高可存储的越少,一般使用Mhints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);// 设置图片边距hints.put(EncodeHintType.MARGIN, 2);try {// 最终生成 参数列表 (1.内容 2.格式 3.宽度 4.高度 5.二维码参数)BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 写入到本地Path file = new File(path).toPath();MatrixToImageWriter.writeToPath(bitMatrix, format, file);return true;} catch (Exception e) {e.printStackTrace();return false;}}}
使用了mian方法测试了,成功生成了二维码图片。