java生成二维码

  • 导入依赖

    • <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 getQR(String text, int width, int height, String filePath) throws WriterException, IOException {
              Hashtable hints = new Hashtable();
              hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
              hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
              hints.put(EncodeHintType.MARGIN, 1);
      
      	//hints对象可以解决二维码内容中文乱码问题
      
              QRCodeWriter qrCodeWriter = new QRCodeWriter();
      
              BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height,hints);
      
              Path path = FileSystems.getDefault().getPath(filePath);
              System.out.println("path======="+path);
              MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
      
          }
      
  • controller调用:

    • String a="强哥强哥我爱你";
              String fileName= UUID.randomUUID()+".png";
              service.insert2(fileName);
              //将二维码订单图片名称插入数据库中,便于前端回显二维码
              String totalName="D:\\QRCode\\"+fileName;
              qrCode.getQR(a,100,100,totalName);
              //调用工具类,依次传入二维码内容、宽、高、以及要保存在哪个路径
              return "redirect:/toQR2";
      
posted @ 2021-12-09 13:32  侑手  阅读(180)  评论(0)    收藏  举报