在Java中生成二维码的一种常用方式是使用Google的ZXing库。以下是一个简单的例子,展示了如何使用该库生成一个二维码图像。
首先,确保你的项目中包含了ZXing依赖。如果你使用Maven,可以在pom.xml中添加以下依赖:
(1)在pom.xml添加依赖
<!-- zxing生成二维码 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
(2)二维码工具类QRCodeUtil,生成的二维码可以直接浏览查看。以下是生成二维码代码:
package com.jing.cloud.controller;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName: QRCodeUtil
* @Description: 二维码工具类
* @Auther: zhshangjing
* @Date: 2024/8/12 16:32
*/
public class QRCodeUtil {
public static void main(String[] args) {
System.out.println(generateQRCodeBase64("https://www.baidu.com"));
}
public static String generateQRCodeBase64(String url) {
String base64Image = "";
try {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = qrCodeWriter.encode(url, BarcodeFormat.QR_CODE, 200, 200, hints);
Path path = FileSystems.getDefault().getPath("qrcode.png");
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
BufferedImage bufferedImage = ImageIO.read(path.toFile());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
byte[] bytes = byteArrayOutputStream.toByteArray();
base64Image = "data:image/png;base64," + Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
e.printStackTrace();
}
return base64Image;
}
}