欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java利用zxing生成二维码

程序员文章站 2022-07-14 17:22:27
...

首先需要相应jar包

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>

直接写在controller里面的二维码生成

private static final int WIDTH = 60;
	   
    private static final int HEIGHT = 60;

	private static final String CHARSET = "UTF-8";
    
	private static final String FORMAT_NAME = "JPG";
	@GetMapping(value = "/showQRCode/{id}")
	public void showQRCode(@PathVariable("id") String id,HttpServletResponse resp) throws Exception {
		GadleeSignAddress gadleeSignAddress = districtService.selectRegionById(id);
		String content = gadleeSignAddress.toString();
		Map<EncodeHintType,Object> config = new HashMap<>();
		config.put(EncodeHintType.CHARACTER_SET,CHARSET);//字符编码
		config.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//纠错等级
		config.put(EncodeHintType.MARGIN, 0);
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,WIDTH,HEIGHT,config);
		Path file = new File("g:/QRCode"+File.separator+IdGen.uuid()+".png").toPath();
		MatrixToImageWriter.writeToPath(bitMatrix,FORMAT_NAME,file);
		System.out.println("二维码生成完毕,已经保存至相关路径中。");
//		下面是将其path保存到数据库,并以流的形式返回给前端,这里需要HttpServletResponse的相应输出流
		File filePath=new File(file.toString());
		String path=filePath.getAbsolutePath();
		GadleeSignAddress gsa = new GadleeSignAddress();
		gsa.setId(id);
		gsa.setName(gadleeSignAddress.getName());
		gsa.setCustomer(gadleeSignAddress.getCustomer());
		gsa.setPath(path);
		districtService.savePath(gsa);
		OutputStream os = resp.getOutputStream();//取得输出流
		MatrixToImageWriter.writeToStream(bitMatrix, FORMAT_NAME, os);//写入文件刷新
		}

        然后优化提出来一个二维码生成的工具类,和controller,这里考虑了既要将二维码显示在前端,也要将二维码保存下来,并将路径保存到相应数据库中

工具类如下:

package com.topband.cloud.common.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class QRCodeUtil {
	
	private static final int WIDTH = 60;
   
    private static final int HEIGHT = 60;

	private static final String CHARSET = "UTF-8";
    
	public static final String FORMAT_NAME = "JPG";
	
	
	public static Map<String,Object> createQRCode(String content) throws Exception {
	Map<EncodeHintType,Object> config = new HashMap<>();
	config.put(EncodeHintType.CHARACTER_SET,CHARSET);//字符编码
	config.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//纠错等级
	config.put(EncodeHintType.MARGIN, 0);
	BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,WIDTH,HEIGHT,config);
	Path file = new File("g:/QRCode"+File.separator+IdGen.uuid()+".png").toPath();
	MatrixToImageWriter.writeToPath(bitMatrix,FORMAT_NAME,file);
	System.out.println("二维码生成完毕,已经保存至相关路径中。");
	File filePath=new File(file.toString());
	String path=filePath.getAbsolutePath();
	Map<String,Object> data = new HashMap<String,Object>();
	data.put("qrcode", bitMatrix);
	data.put("path", path);
	return data;
}
}

如上代码为了在controller中保存路径到数据库,同时为了将二维码刷新到前端,故而将路径和二维码生成的图像通过map返回来,在controller中取出并作适当类型转换,然后就可以实现。

controller代码如下:

@GetMapping(value = "/showQRCode/{id}")
	public void showQRCode(@PathVariable("id") String id,HttpServletResponse resp) throws Exception {
		GadleeSignAddress gadleeSignAddress = districtService.selectRegionById(id);
		String content = gadleeSignAddress.toString();
		Map<String,Object> data = QRCodeUtil.createQRCode(content);
		String path = (String) data.get("path");
		BitMatrix bitMatrix = (BitMatrix) data.get("qrcode");
		GadleeSignAddress gsa = new GadleeSignAddress();
		gsa.setId(id);
		gsa.setName(gadleeSignAddress.getName());
		gsa.setCustomer(gadleeSignAddress.getCustomer());
		gsa.setPath(path);
		districtService.savePath(gsa);
		OutputStream os = resp.getOutputStream();//取得输出流
		MatrixToImageWriter.writeToStream(bitMatrix, QRCodeUtil.FORMAT_NAME, os);//写入文件刷新
		}

测试均ok,如下

java利用zxing生成二维码

解析二维码的代码也放上

//	解析二维码
    public static void readQRCode(File file){
    	
    	try {
    		MultiFormatReader formatReader = new MultiFormatReader();
			BufferedImage image = ImageIO.read(file);
			BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
			HashMap hints = new HashMap();
			hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
			Result result = formatReader.decode(binaryBitmap, hints);
			} catch (NotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }