Springboot + zxing 生成二维码

1 引入依赖

<!-- 二维码相关 -->
<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 生成二维码

try {
// 二维码的宽高
int width = 300;
int height = 300;
// 二维码内容
String content = "这是一个测试二维码";
// 二维码图片的格式
String format = "png";
// 定义二维码参数
HashMap<EncodeHintType, Object> hints = new HashMap<>();
// 字符编码
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//纠错等级,二维码受到污染后的识别准确度,自行了解后修改
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
// 边距
hints.put(EncodeHintType.MARGIN, 2);
// 颜色设置(二维码颜色,图片背景颜色)
MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig(0xFF161B2A,0x00FFFFFF);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
// 二维码输出的路径
Path file = new File("D:\\image\\img.png").toPath();
// 将二维码进行输出
MatrixToImageWriter.writeToPath(bitMatrix, format, file,matrixToImageConfig);
} catch (Exception e) {
e.printStackTrace();
}

3 读取二维码

try {
MultiFormatReader formatReader = new MultiFormatReader();
File file = new File("D:\\image\\img.png");
BufferedImage image = null;
image = ImageIO.read(file);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
// 定义二维码的参数
HashMap<DecodeHintType,Object> hints = new HashMap<>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
Result result = formatReader.decode(binaryBitmap, hints);
System.out.println("解析结果: " + result.toString());
System.out.println("二维码格式类型:" + result.getBarcodeFormat());
System.out.println("二维码文本内容:" + result.getText());
} catch (Exception e) {
e.printStackTrace();
}
posted @   鱼鱼寡欢  阅读(145)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
点击右上角即可分享
微信分享提示