Java--生成二维码(zxing方式)

来源:互联网 发布:淘宝话费充值店利润 编辑:程序博客网 时间:2024/06/05 16:58

上篇博客生成的jar包放到工程当中,记得添加到buildpath当中。如下图所示。


           新建一个类来测试生成二维码,代码如下。

[html] view plain copy
  1. package com.qrcode;  
  2.   
  3. import java.io.File;  
  4. import java.nio.file.Path;  
  5. import java.util.HashMap;  
  6.   
  7. import com.google.zxing.BarcodeFormat;  
  8. import com.google.zxing.EncodeHintType;  
  9. import com.google.zxing.MultiFormatWriter;  
  10. import com.google.zxing.client.j2se.MatrixToImageWriter;  
  11. import com.google.zxing.common.BitMatrix;  
  12. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;  
  13.   
  14. public class CreateQrCode {  
  15.     public static void main(String[] args){  
  16.         //设置二维码像素  
  17.         int width = 300;  
  18.         int height = 300;  
  19.         //要生成什么格式的二维码  
  20.         String format = "png";  
  21.         //二维码当中要存储什么信息  
  22.         String content = "http://www.baidu.com";  
  23.         HashMap hints = new HashMap();  
  24.         hints.put(EncodeHintType.CHARACTER_SET, "utf-8");  
  25.         //设置纠错率,分为L、M、H三个等级,等级越高,纠错率越高,但存储的信息越少  
  26.         hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);  
  27.         //设置一下边距,默认是5  
  28.         hints.put(EncodeHintType.MARGIN, 2);  
  29.         try {  
  30.             BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);  
  31.             Path file = new File("E:/code/qrcode.png").toPath();//前提是E盘下有code这个目录  
  32.             MatrixToImageWriter.writeToPath(bitMatrix, format, file);  
  33.         } catch (Exception e) {  
  34.             e.printStackTrace();  
  35.         }  
  36.     }  
  37. }  

       运行上面的代码后我们到E盘的code目录下查看生成的二维码,如下图所示。我们扫描它便可以进入百度首页了。

原创粉丝点击