Java实现二维码生成

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gisboygogogo/article/details/86036656

本篇文章将介绍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”二维码,并保存在桌面,如下图:

上面的方法是将二维码保存为图片,如果你不想将二维码保存为图片,也可以将其保存为字节数组,可以用zxing 库提供的MatrixToImageWriter.writeToStream()方法:

    public static byte[] getQRCodeImage(String text, int width, int height) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
        byte[] pngData = pngOutputStream.toByteArray(); 
        return pngData;
    }

这个方法可以将字节数组在web页面展示为图片形式。结合Spring Boot + Thymeleaf搭建的web工程,如果想在页面显示该二维码信息的话,需要在html页面和controller中完成如下代码:

qrcode.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"/>
    <script type="text/javascript" src="webjars/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<div th:replace="fragments/header :: header"></div>
<div class="container">
    <div class="starter-template">
        <h1>QrCodeImage</h1>
    </div>
</div>
<div class="container">
	<img alt="qrcode" th:src="@{'/qrimage'}" />
    <footer>
        <p>
            © <a >ThinkingInGIS</a> 2019
        </p>
    </footer>
</div>
</body>
</html>

DefaultController.java

   @GetMapping("qrcode")
    public String qrcode() {
    	return "/qrcode";
    }
    
    @GetMapping(value="/qrimage")
	public ResponseEntity<byte[]> getQRImage() {
		
		//二维码内的信息
		String info = "This is my first QR Code";
		
		byte[] qrcode = null;
		try {
			qrcode = QRCodeGenerator.getQRCodeImage(info, 360, 360);
		} catch (WriterException e) {
			System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
		} 

	    // Set headers
	    final HttpHeaders headers = new HttpHeaders();
	    headers.setContentType(MediaType.IMAGE_PNG);

	    return new ResponseEntity<byte[]> (qrcode, headers, HttpStatus.CREATED);
	}

请注意qrcode.html中<img>标签中 src属性的值。

启动spring boot程序,访问该页面,运行结果如下图:

源码地址:https://github.com/ThinkingInGIS/spring-boot-security

至此,一个简单的生成二维码程序,并在web中展示的功能就搭建好了。
(如遇到问题,请留言给作者,以便共同探讨gis知识。[email protected])
更多干货 欢迎关注微信公众号: ThinkingInGIS

如果觉得本文对你有帮助,是可以赞赏作者的哦

猜你喜欢

转载自blog.csdn.net/gisboygogogo/article/details/86036656
今日推荐