zoukankan      html  css  js  c++  java
  • zxing实现java二维码生成和解析

    转自:https://blog.csdn.net/javaweiming/article/details/72844581

    生成二维码的方式有很多,在此简单介绍Google的zxing使用

    先加载需要用到的包,pom.xml文件里面添加:

    1. <!-- 二维码生成 -->
    2. <dependency>
    3. <groupId>com.google.zxing</groupId>
    4. <artifactId>core</artifactId>
    5. <version>2.2</version>
    6. </dependency>
    7.  
    8. <dependency>
    9. <groupId>com.google.zxing</groupId>
    10. <artifactId>javase</artifactId>
    11. <version>2.2</version>
    12. </dependency>


    工具类代码

    1. import java.awt.image.BufferedImage;
    2. import java.io.File;
    3. import java.io.IOException;
    4. import java.nio.file.FileSystems;
    5. import java.nio.file.Path;
    6. import java.util.HashMap;
    7. import java.util.Map;
    8.  
    9. import javax.imageio.ImageIO;
    10.  
    11. import com.google.zxing.BarcodeFormat;
    12. import com.google.zxing.Binarizer;
    13. import com.google.zxing.BinaryBitmap;
    14. import com.google.zxing.DecodeHintType;
    15. import com.google.zxing.EncodeHintType;
    16. import com.google.zxing.LuminanceSource;
    17. import com.google.zxing.MultiFormatReader;
    18. import com.google.zxing.MultiFormatWriter;
    19. import com.google.zxing.NotFoundException;
    20. import com.google.zxing.Result;
    21. import com.google.zxing.WriterException;
    22. import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
    23. import com.google.zxing.client.j2se.MatrixToImageWriter;
    24. import com.google.zxing.common.BitMatrix;
    25. import com.google.zxing.common.HybridBinarizer;
    26. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
    27.  
    28. import net.sf.json.JSONObject;
    29.  
    30. /**
    31. *
    32. * 处理图片url
    33. */
    34. public class QRCodeUtil {
    35.  
    36. public static void main(String[] args) throws WriterException, IOException {
    37. testEncode();
    38. testDecode();
    39. }
    40.  
    41. /**
    42. * 生成图像
    43. *
    44. * @throws WriterException
    45. * @throws IOException
    46. */
    47. public static void testEncode() throws WriterException, IOException {
    48. String filePath = "D://";
    49. String fileName = "text.png";
    50. JSONObject json = new JSONObject();
    51. json.put("url", "https://www.baidu.com");
    52. json.put("author", "zwm");
    53. String content = json.toString();// 内容
    54. int width = 200; // 图像宽度
    55. int height = 200; // 图像高度
    56. String format = "png";// 图像类型
    57. Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
    58. hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    59. BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
    60. Path path = FileSystems.getDefault().getPath(filePath, fileName);
    61. File file = new File(filePath + fileName);
    62. MatrixToImageWriter.writeToFile(bitMatrix, format, file);// 输出图像
    63. System.out.println("图片文件已经生成.请于D盘查找");
    64. }
    65.  
    66. /**
    67. * 解析图像
    68. */
    69. public static void testDecode() {
    70. String filePath = "D://text.png";
    71. BufferedImage image;
    72. try {
    73. image = ImageIO.read(new File(filePath));
    74. LuminanceSource source = new BufferedImageLuminanceSource(image);
    75. Binarizer binarizer = new HybridBinarizer(source);
    76. BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
    77. Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
    78. hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
    79. Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
    80. JSONObject content = JSONObject.fromObject(result.getText());
    81. System.out.println("图片中内容: ");
    82. System.out.println("author:" + content.getString("author"));
    83. System.out.println("url: " + content.getString("url"));
    84. System.out.println("图片中格式: ");
    85. System.out.println("encode: " + result.getBarcodeFormat());
    86. } catch (IOException e) {
    87. e.printStackTrace();
    88. } catch (NotFoundException e) {
    89. e.printStackTrace();
    90. }
    91. }
    92.  
    93. public static BufferedImage createQRCode(final String url) throws WriterException, IOException {
    94. BufferedImage image = null;
    95. // 二维码图片输出流
    96. MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
    97. HashMap<EncodeHintType, Comparable> hints = new HashMap<EncodeHintType, Comparable>();
    98. // 设置编码方式
    99. hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    100. // 设置QR二维码的纠错级别(H为最高级别)具体级别信息
    101. hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
    102. BitMatrix bitMatrix = multiFormatWriter.encode(url, BarcodeFormat.QR_CODE, 400, 400, hints);
    103. bitMatrix = updateBit(bitMatrix, 10);
    104. image = MatrixToImageWriter.toBufferedImage(bitMatrix);
    105. return image;
    106. }
    107.  
    108. /**
    109. * 自定义白边边框宽度
    110. *
    111. * @param matrix
    112. * @param margin
    113. * @return
    114. */
    115. private static BitMatrix updateBit(final BitMatrix matrix, final int margin) {
    116. int tempM = margin * 2;
    117. // 获取二维码图案的属性
    118. int[] rec = matrix.getEnclosingRectangle();
    119. int resWidth = rec[2] + tempM;
    120. int resHeight = rec[3] + tempM;
    121. // 按照自定义边框生成新的BitMatrix
    122. BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
    123. resMatrix.clear();
    124. // 循环,将二维码图案绘制到新的bitMatrix中
    125. for (int i = margin; i < resWidth - margin; i++) {
    126. for (int j = margin; j < resHeight - margin; j++) {
    127. if (matrix.get(i - margin + rec[0], j - margin + rec[1])) {
    128. resMatrix.set(i, j);
    129. }
    130. }
    131. }
    132. return resMatrix;
    133. }
    134. }


    直接运行即可看到效果,其中 createQRCode是用于直接将生成的二维码以流的形式在页面上输出,调用方法如下:

    1. /**
    2. * 根据URL生成二维码
    3. * @param model
    4. * @param request
    5. * @param response
    6. * @throws MaHuaServiceHandleException
    7. */
    8. @RequestMapping("/getQRCode")
    9. public void getQRCode(final @RequestAttribute(ReqBean.NAME) ReqBean reqBean,HttpServletRequest request, HttpServletResponse response){
    10. String url = "http://www.baidu.com";
    11. //二维码图片输出流
    12. OutputStream out = null;
    13. try{
    14. response.setContentType("image/jpeg;charset=UTF-8");
    15. BufferedImage image = QRCodeUtil.createQRCode(url);
    16. //实例化输出流对象
    17. out = response.getOutputStream();
    18. //画图
    19. ImageIO.write(image, "png", response.getOutputStream());
    20. out.flush();
    21. out.close();
    22. }catch (Exception e){
    23. e.printStackTrace();
    24. }finally {
    25. try{
    26. if (null != response.getOutputStream()) {
    27. response.getOutputStream().close();
    28. }
    29. if (null != out) {
    30. out.close();
    31. }
    32. }catch(Exception e){
    33. e.printStackTrace();
    34. }
    35. }
    36. }


     在页面上调用此方法:

     <div style="height:100%;100%"><img style="100%" id="QRCode" src="./activity/getQRCode.do?" /></div>  


      这样生成的二维码则会再这个div的地方显示出来

  • 相关阅读:
    数据分析2 numpy(ndarray数组,属性,创建,索引切片,运算,函数,随机数), Pandas(Series[创建,series数据对齐(相加),缺失值处理,特性,索引[整数索引loc和iloc]],DataFrame[索引与切片, 常用属性,数据对齐(相加),缺失值处理,常用方法],时间对象,时间序列), dateutil时间处理
    数据分析1 ipython, jupyter notebook(快捷键), anaconda软件
    CMDB4 总结CMDB,数据展示前后端不分离(xadmin第二种安装方法),前后端分离(vue-element-admin,iview-admin), 画图工具(highcharts,echarts,antv)
    CMDB3 完善采集端代码(ssh方案的多线程采集), 异常处理, 服务端目录结构的设计(django的app), API数据分析比对入库
    CMDB2 采集客户端目录架构设计, 高级配置文件, 可插拔式的采集
    CentOS, CMDB1 Linux命令补充(netstat,ps,kill,service,systemctl,top,wget,Irzsz,vim,磁盘使用情况,cpu情况,tree,history),linux常见的面试题, CMDB
    CentOS centos7的目录结构, 文件系统常用命令(pwd,cd,mkdir,touch,ls,cat,echo,cp,mv,rm), vim编辑器
    CentOS VMware安装CentOS7,配置网卡文件,Xshell5连接,快照,克隆,修改主机名
    flask框架4 表单验证, 表单查询wtforms,flask-migrate
    flask框架3 local对象补充,偏函数,请求上下文,g对象,flask-session组件,flask的信号,自定义信号(了解),用命令启动flask项目(flask-script)
  • 原文地址:https://www.cnblogs.com/yangsanluo/p/14282635.html
Copyright © 2011-2022 走看看