创建二维码
依赖导入
<dependency>
<groupId>com.google.zxinggroupId>
<artifactId>coreartifactId>
<version>3.4.1version>
dependency>
<dependency>
<groupId>com.google.zxinggroupId>
<artifactId>javaseartifactId>
<version>3.4.1version>
dependency>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
工具类
package com.sin.util;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class QRCodeUtil {
private static final int WIDTH = 300;
private static final int HEIGHT = 300;
private static final String FORMAT = "png";
public static void generateQRCode(String text, String filePath) {
try {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 2);
BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
BufferedImage image = toBufferedImage(bitMatrix);
File file = new File(filePath);
ImageIO.write(image, FORMAT, file);
System.out.println("二维码已生成,保存路径:" + filePath);
} catch (Exception e) {
e.printStackTrace();
}
}
private static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
boolean pixel = matrix.get(x, y);
int rgb = pixel ? Color.BLACK.getRGB() : Color.WHITE.getRGB();
image.setRGB(x, y, rgb);
}
}
return image;
}
}

- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
测试
package com.sin.test;
import com.sin.util.QRCodeUtil;
public class QRCodeExample {
public static void main(String[] args) {
String text = "https://blog.csdn.net/qq_44715376?spm=1000.2115.3001.5343";
String filePath = "D:/qrcode.png";
QRCodeUtil.generateQRCode(text, filePath);
System.out.println("生成成功");
}
}
生成的二维码
