zoukankan      html  css  js  c++  java
  • Java实现二维码生成

    本篇文章将介绍java中如何生成二维码,二维码的展示主要包括两方面:

    1.直接生成图片(直接生成图片不需要web程序,maven工程即可)

    2.将二维码转为字节数组,然后在web页面显示。web项目的目录结构以前面的一篇文章中的目录结构为基础(传送门)。生成二维码的功能主要是依赖Google的Zxing包。

    1.添加Zxing的依赖(maven工程为例)

     
            <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>
     

    2.保存信息为二维码图片

    名为generateQRCodeImage方法,将字符串封装成二维码、设置二维码的宽度和高度、声明二维码保存的路径与图片名称。

     
    package org.thinkingingis.utils;
     
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.nio.file.FileSystems;
    import java.nio.file.Path;
     
    import com.google.zxing.BarcodeFormat;
    import com.google.zxing.WriterException;
    import com.google.zxing.client.j2se.MatrixToImageWriter;
    import com.google.zxing.common.BitMatrix;
    import com.google.zxing.qrcode.QRCodeWriter;
     
    public class QRCodeGenerator {
        
        private static final String QR_CODE_IMAGE_PATH = "/Users/gisboy/Desktop/MyQRCode.png";
        
        private static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            
            BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
            
            Path path = FileSystems.getDefault().getPath(filePath);
            
            MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
            
        }
        
        public static void main(String[] args) {
            try {
                generateQRCodeImage("This is my first QR Code", 350, 350, QR_CODE_IMAGE_PATH);
            } catch (WriterException e) {
                System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
            } catch (IOException e) {
                System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
            }
            
        }
        
     
    }
     

    上面的代码将会生成一个内容为“This is my first QR Code”二维码,并保存在桌面,如下图:

  • 相关阅读:
    浮动广告
    jQuery给table添加行和删除行
    oracle优化方式和sql标准
    使用JavaScript中的ActiveXObject填充并设置Excel格
    打印相关的js
    利用js导出Excel
    Oracle左外连接和右外连接的写法
    天气预报抓取的方法和源代码(包括从IP获取)
    algorithm
    ungetc
  • 原文地址:https://www.cnblogs.com/liuys635/p/15398427.html
Copyright © 2011-2022 走看看