使用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.youkuaiyun.com/chenhao_c_h";

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值