生成二维码
需要引入相关包:
<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.0</version> </dependency>
代码如下:
public static void main(String[] args) throws Exception { SimpleDateFormat sim = new SimpleDateFormat(); String contents = "测试:" + sim.format(new Date()) + "\n测试1:" + 123 + " \n测试2:是否是客服电话"; //String contents = "测试:" + sim.format(new Date()) + "测试1:" + 123 + " 测试2:是否是客服电话";
//String contents = "https://www.baidu.com" // 如果不用更改源码,将字符串转换成ISO-8859-1编码 contents = new String(contents.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); int width = 300, height = 300; QRCodeController handler = new QRCodeController(); //handler.encode(contents, width, height, imgPath);
// 转为图片
try {
/*StringUtils.isNumber(imgPath) ? "C:/Users/Administrator/Desktop/QR/123.png" : imgPath;*/
BitMatrix bitMatrix = new MultiFormatWriter().encode(String.valueOf(contents),
BarcodeFormat.QR_CODE, width, height);
MatrixToImageWriter
.writeToFile(bitMatrix, "png", new File("C:/Users/Administrator/Desktop/QR/123.png"));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("生成二维码成功!");
}
生成二维码如下:
注意点:
数据无法传入集合,当前通过字符串形式进行展示,其中\n会进行换行操作如代码红色字体部位图片效果如下:
若是没有 \n 效果如下图:
若是扫描二维码跳转页面,只需要将字符串数据换为链接即可 如代码部分蓝色字体 如下图:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?