import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
public class QRCodeGenerator {
public static void main(String[] args) {
String data = "https://www.example.com"; // 二维码要包含的数据
int width = 300; // 图片宽度
int height = 300; // 图片高度
String filePath = "qrcode.png"; // 输出文件路径
try {
createQRCode(data, width, height, filePath);
System.out.println("二维码图片已生成!");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void createQRCode(String data, int width, int height, String filePath) throws Exception {
// 设置二维码的参数
Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 创建BitMatrix对象
BitMatrix matrix = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, width, height, hints);
// 创建BufferedImage对象
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
// 设置背景色为白色
graphics.setColor(java.awt.Color.WHITE);
graphics.fillRect(0, 0, width, height);
// 设置前景色为黑色,并绘制二维码
graphics.setColor(java.awt.Color.BLACK);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (matrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
// 将BufferedImage保存为PNG格式的文件
File file = new File(filePath);
ImageIO.write(image, "png", file);
}
}
com.google.zxing
包来生成二维码,javax.imageio.ImageIO
用于图像处理。MultiFormatWriter
类生成二维码的 BitMatrix
对象,并设置了字符集为 UTF-8。BufferedImage
对象并使用 Graphics2D
绘制二维码。背景色设为白色,前景色设为黑色。zxing
库,可以通过 Maven 或直接下载 jar 包引入。上一篇:java 拆分字符串
下一篇:java mqtt协议
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站