java二维码生成工具类
时间: 2023-09-23 20:03:12 浏览: 56
以下是一个Java二维码生成工具类的示例代码:
```java
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 {
/**
* 生成二维码图片
* @param text 二维码内容
* @param width 二维码宽度
* @param height 二维码高度
* @param filePath 二维码保存路径
* @throws WriterException
* @throws IOException
*/
public static void generateQRCode(String text, int width, int height, String filePath) throws WriterException, IOException {
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);
QRCodeWriter writer = new QRCodeWriter();
BitMatrix matrix = writer.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
}
}
File file = new File(filePath);
ImageIO.write(image, "png", file);
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
try {
QRCodeGenerator.generateQRCode("https://www.example.com", 200, 200, "qrcode.png");
System.out.println("二维码生成成功");
} catch (Exception e) {
System.out.println("二维码生成失败:" + e.getMessage());
}
}
}
```
该工具类使用了Google的ZXing库来生成二维码图片。其中,`generateQRCode`方法接收四个参数:二维码内容、二维码宽度、二维码高度和二维码保存路径。方法中首先根据参数生成`BitMatrix`对象,然后根据`BitMatrix`对象生成`BufferedImage`对象,并将其保存到指定路径。