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.client.j2se.MatrixToImageWriter;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
public class QRCodeGenerator {
public static void main(String[] args) {
String data = "https://www.example.com";
String path = "QRCode.png";
int width = 300;
int height = 300;
String format = "png";
try {
Map<EncodeHintType, Object> hintMap = new HashMap<>();
hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(data, BarcodeFormat.QR_CODE, width, height, hintMap);
Path outputPath = FileSystems.getDefault().getPath(path);
MatrixToImageWriter.writeToPath(bitMatrix, format, outputPath);
System.out.println("二维码已生成: " + path);
} catch (WriterException | IOException e) {
System.err.println("生成二维码时出错: " + e.getMessage());
}
}
}
com.google.zxing 包中的类来生成二维码。这个包是 ZXing(Zebra Crossing)库的一部分,提供了强大的条码和二维码生成功能。data 和保存二维码图像的路径 path。hintMap 设置字符集为 UTF-8,确保支持多语言字符。QRCodeWriter 类生成二维码,并将其转换为位矩阵 BitMatrix。MatrixToImageWriter 将位矩阵写入指定路径,保存为 PNG 图像文件。请确保你已经添加了 ZXing 库到你的项目中,可以通过 Maven 或直接下载 jar 文件来引入该库。
上一篇:java jar运行
下一篇:split()函数用法java
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站