使用java生成二维码


如何使用java快速生成我们想要的二维码,仅需一个类

1.首先引入包

<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>javase</artifactId>
  <version>3.2.1</version>
</dependency>

2.然后上代码

 
 
public class CreateQRcode {

  public static void main(String[] args) {
    //图片大小.
    int width = 300;
    int height = 300;
    //图片格式.
    String format = "png";
    //想输出的内容.
    String content = "hello world!";

    //定义二维码的参数.
    HashMap hints = new HashMap();
    //设置中文.
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    //设置纠错等级,H最高 但是存储内容最少.
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
    //设置边距.
    hints.put(EncodeHintType.MARGIN, 2);

    try {
      BitMatrix bitMatrix = new MultiFormatWriter()
          .encode(content, BarcodeFormat.QR_CODE, width, height, hints);
      //文件位置,目录不存在会抛出异常.
      Path file = new File("/Users/chenhao/img.png").toPath();
      MatrixToImageWriter.writeToPath(bitMatrix, format, file);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}
 
 

也可以是一个url,只需要将想输出的内容换成url,即可实现跳转。例如

 
 
String content = "https://blog.csdn.net/chenhao_c_h";

附上git地址:https://github.com/ChenHaoXFN/creatrQRcode

猜你喜欢

转载自blog.csdn.net/chenhao_c_h/article/details/79784447