Java生成网站二维码
先在pom文件中添加依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.5.1</version>
</dependency>
以下是工具类代码
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
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.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class QRCodeGenerator {
// 生成二维码并保存为图片文件
public static void generateQRCodeImage(String url, int width, int height, String filePath)
throws WriterException, IOException {
// 设置二维码参数
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高容错级别
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 字符编码
hints.put(EncodeHintType.MARGIN, 1); // 边距
// 创建QRCodeWriter对象
QRCodeWriter qrCodeWriter = new QRCodeWriter();
// 生成二维码矩阵
BitMatrix bitMatrix = qrCodeWriter.encode(url, BarcodeFormat.QR_CODE, width, height, hints);
// 创建 BufferedImage 对象
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
// 设置绘图颜色
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
graphics.setColor(Color.BLACK);
// 绘制二维码
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (bitMatrix.get(j, i)) {
graphics.fillRect(j, i, 1, 1);
}
}
}
// 保存二维码图片
File qrCodeFile = new File(filePath);
ImageIO.write(image, "PNG", qrCodeFile);
}
public static void main(String[] args) {
try {
// 要生成二维码的网址
String url = "http://www.baidu.com";
// 生成二维码,尺寸为300x300像素,保存为qrcode.png
generateQRCodeImage(url, 1000, 1000, "D://qrcode.png");
System.out.println("二维码生成成功!");
} catch (WriterException e) {
System.out.println("生成二维码时发生错误: " + e.getMessage());
} catch (IOException e) {
System.out.println("保存二维码图片时发生错误: " + e.getMessage());
}
}
}