生成二维码

 需要引入相关包:

        <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 效果如下图:

            

 

若是扫描二维码跳转页面,只需要将字符串数据换为链接即可  如代码部分蓝色字体 如下图:

  

 

posted @ 2022-01-25 16:50  RM-RF?  阅读(30)  评论(0编辑  收藏  举报