最下面是纯二维码
配置pom文件
<!-- 二维码工具类 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.0</version>
</dependency>
创建工具类
第一种方式
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.csdn.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("F:/img.png").toPath(); //设置路径
MatrixToImageWriter.writeToPath(bitMatrix, format, file); //输出图像
} catch (Exception e) {
e.printStackTrace();
}
}
}
第二种方式
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class QrCodeUtil {
public static byte[] createQRCode(int width, int height, String content) throws WriterException, IOException {
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码字符集utf-8
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);// 设置纠错等级L/M/Q/H,纠错等级越高越不易识别,当前设置等级为最高等级H
hints.put(EncodeHintType.MARGIN, 0);// 可设置范围为0-10,但仅四个变化0 1(2) 3(4 5 6) 7(8 9 10)
// 生成图片类型为QRCode
BarcodeFormat format = BarcodeFormat.QR_CODE;
// 创建位矩阵对象
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, format, width, height, hints);
ByteArrayOutputStream os = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "png", os);
return os.toByteArray();
}
public static void main(String[] args) throws WriterException, IOException {
byte[] b = createQRCode(100, 100, "遇见最好的自己!");
OutputStream os = new FileOutputStream("E:\\bestme.png");
os.write(b);
os.close();
}
}