QrCodeMaker.java 5.6 KB
Newer Older
Z
1.0.0  
zhuangqian 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/**
 * Copyright (c) 2011-2017, James Zhan 詹波 (jfinal@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
S
smallchill 已提交
16
package org.springblade.core.toolbox.qrcode;
Z
1.0.0  
zhuangqian 已提交
17 18 19 20 21 22 23

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
S
smallchill 已提交
24
import org.springblade.core.toolbox.kit.StrKit;
Z
1.0.0  
zhuangqian 已提交
25

26 27 28 29
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

Z
1.0.0  
zhuangqian 已提交
30 31
/**
 * QrCode 生成二维码
32
 * @author jfinal
Z
1.0.0  
zhuangqian 已提交
33
 */
34
public class QrCodeMaker {
Z
1.0.0  
zhuangqian 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48
	
	private HttpServletResponse response;
	
	private String content;
	private int width;
	private int height;
	private ErrorCorrectionLevel errorCorrectionLevel;

	/**
	 * 构造方法,经测试不指定纠错参数时,默认使用的是 'L' 最低级别纠错参数
	 * @param content 二维码携带内容
	 * @param width 二维码宽度
	 * @param height 二维码高度
	 */
49 50
	public static QrCodeMaker init(HttpServletResponse response, String content, int width, int height) {
		return new QrCodeMaker(response, content, width, height);
Z
1.0.0  
zhuangqian 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64
	}
	
	/**
	 * 带有纠错级别参数的构造方法,生成带有 logo 的二维码采用纠错原理
	 * 使用 ErrorCorrectionLevel.H 参数提升纠错能力
	 *
	 * ErrorCorrectionLevel 是枚举类型,纠错能力从高到低共有四个级别:
	 *  H = ~30% correction
	 *  Q = ~25% correction
	 *  M = ~15% correction
	 *  L = ~7%
	 *
	 *  使用的时候直接这样:ErrorCorrectionLevel.H
	 */
65 66
	public static QrCodeMaker init(HttpServletResponse response, String content, int width, int height, ErrorCorrectionLevel errorCorrectionLevel) {
		return new QrCodeMaker(response, content, width, height, errorCorrectionLevel);
Z
1.0.0  
zhuangqian 已提交
67 68 69 70 71
	}
	
	/**
	 * 带有纠错级别参数的构造方法,纠错能力从高到低共有四个级别:'H'、'Q'、'M'、'L'
	 */
72 73
	public static QrCodeMaker init(HttpServletResponse response, String content, int width, int height, char errorCorrectionLevel) {
		return new QrCodeMaker(response, content, width, height, errorCorrectionLevel);
Z
1.0.0  
zhuangqian 已提交
74 75 76
	}
	

77
	private QrCodeMaker(HttpServletResponse response, String content, int width, int height) {
Z
1.0.0  
zhuangqian 已提交
78 79 80 81
		initialize(response, content, width, height, null);
	}


82
	private QrCodeMaker(HttpServletResponse response, String content, int width, int height, ErrorCorrectionLevel errorCorrectionLevel) {
Z
1.0.0  
zhuangqian 已提交
83 84 85 86
		initialize(response, content, width, height, errorCorrectionLevel);
	}


87
	private QrCodeMaker(HttpServletResponse response, String content, int width, int height, char errorCorrectionLevel) {
Z
1.0.0  
zhuangqian 已提交
88 89 90 91
		initialize(response, content, width, height, errorCorrectionLevel);
	}

	private void initialize(HttpServletResponse response, String content, int width, int height, char errorCorrectionLevel) {
92 93 94 95 96
        char H = 'H';
        char Q = 'Q';
        char M = 'M';
        char L = 'L';
	    if (errorCorrectionLevel == H) {
Z
1.0.0  
zhuangqian 已提交
97
			initialize(response, content, width, height, ErrorCorrectionLevel.H);
98
		} else if (errorCorrectionLevel == Q) {
Z
1.0.0  
zhuangqian 已提交
99
			initialize(response, content, width, height, ErrorCorrectionLevel.Q);
100
		} else if (errorCorrectionLevel == M) {
Z
1.0.0  
zhuangqian 已提交
101
			initialize(response, content, width, height, ErrorCorrectionLevel.M);
102
		} else if (errorCorrectionLevel == L) {
Z
1.0.0  
zhuangqian 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
			initialize(response, content, width, height, ErrorCorrectionLevel.L);
		} else {
			throw new IllegalArgumentException("errorCorrectionLevel 纠错级别参数值,从高到低必须为: 'H'、'Q'、'M'、'L'");
		}
	}

	private void initialize(HttpServletResponse response, String content, int width, int height, ErrorCorrectionLevel errorCorrectionLevel) {
		if (StrKit.isBlank(content)) {
			throw new IllegalArgumentException("content 不能为空");
		}
		if (width < 0 || height < 0) {
			throw new IllegalArgumentException("width 与 height 不能小于 0");
		}
		this.response = response;
		this.content = content;
		this.width = width;
		this.height = height;
		this.errorCorrectionLevel = errorCorrectionLevel;
	}

	public void start() {
		response.setHeader("Pragma","no-cache");
		response.setHeader("Cache-Control","no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/png");

129
		Map<EncodeHintType, Object> hints = new HashMap<>(16);
Z
1.0.0  
zhuangqian 已提交
130
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
131 132 133 134
        /**
         * 去掉白色边框,否则二维码周围的白边会很宽
         */
		hints.put(EncodeHintType.MARGIN, 0);
Z
1.0.0  
zhuangqian 已提交
135 136 137 138 139 140 141 142 143 144
		if (errorCorrectionLevel != null) {
			hints.put(EncodeHintType.ERROR_CORRECTION, errorCorrectionLevel);
		}
		try {
			// MultiFormatWriter 可支持多种格式的条形码,在此直接使用 QRCodeWriter,通过查看源码可知少创建一个对象

			QRCodeWriter writer = new QRCodeWriter();
			BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

			// 经测试 200 X 200 大小的二维码使用 "png" 格式只有 412B,而 "jpg" 却达到 15KB
145
			MatrixToImageWriter.writeToStream(bitMatrix, "png", response.getOutputStream());
Z
1.0.0  
zhuangqian 已提交
146 147 148 149 150 151
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
}