import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
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 = "C:\\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");
BitMatrix matrix = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, width, height, hintMap);
Path outputPath = FileSystems.getDefault().getPath(path);
MatrixToImageWriter.writeToPath(matrix, format, outputPath);
System.out.println("二维码已生成: " + path);
} catch (Exception e) {
System.err.println("生成二维码时出错: " + e.getMessage());
}
}
}
导入必要的库:
com.google.zxing.*
:用于生成二维码的核心库。java.nio.file.*
:用于处理文件路径和写入文件。创建 QRCodeGenerator
类:
main
方法,作为程序的入口点。定义二维码数据和其他参数:
data
:要编码为二维码的字符串(例如网址)。path
:生成的二维码图片保存路径。width
和 height
:二维码图片的宽度和高度。format
:图片格式(如 PNG、JPG 等)。设置编码提示:
hintMap
设置字符集为 UTF-8,确保正确编码多语言字符。生成二维码:
MultiFormatWriter
类生成二维码的位矩阵(BitMatrix
)。MatrixToImageWriter
将位矩阵写入指定路径的图片文件中。异常处理:
输出成功信息:
此代码段使用了 ZXing 库来生成二维码。请确保在项目中添加 ZXing 库的依赖项。
上一篇:java for
下一篇:java pdf
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站