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(); |
| } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤